note 91950 added to function.preg-replace-callback

From: Date: Thu, 02 Jul 2009 15:02:24 +0000
Subject: note 91950 added to function.preg-replace-callback
Groups: php.notes 
Request: Send a blank email to php-notes+get-157830@lists.php.net to get a copy of this message
A simple function to replace a list of complete words or terms in a string (for PHP 5.3 or above because of the closure): <?php function replace_words($list, $line, $callback) { return preg_replace_callback( '/(^|[^\\w\\-])(' . implode('|', array_map('preg_quote', $list)) . ')($|[^\\w\\-])/mi', function($v) use ($callback) { return $v[1] . $callback($v[2]) . $v[3]; }, $line ); } ?> Example of usage: <?php $list = array('php', 'apache web server'); $str = "php and the apache web server work fine together. php-gtk, for example, won't match. apache web servers shouldn't too."; echo replace_words($list, $str, function($v) { return "<strong>{$v}</strong>"; }); ?> ---- Server IP: 130.206.1.5 Probable Submitter: 89.140.161.225 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace-callback.php Edit -- https://master.php.net/note/edit/91950 Del: integrated -- https://master.php.net/note/delete/91950/integrated Del: useless -- https://master.php.net/note/delete/91950/useless Del: bad code -- https://master.php.net/note/delete/91950/bad+code Del: spam -- https://master.php.net/note/delete/91950/spam Del: non-english -- https://master.php.net/note/delete/91950/non-english Del: in docs -- https://master.php.net/note/delete/91950/in+docs Del: other reasons-- https://master.php.net/note/delete/91950 Reject -- https://master.php.net/note/reject/91950 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#157830) next »