PHP: Regex Find and Replace any Word (string or text) at one go

How to achieve find and replace in one go? I tried searching for find and replace at a time then I could not find the direct answer on net. There is find/search at a time or replace. I want to do both.

PHP regular expression function preg_replace_callback() can achieve this find and replace task in one shot. I have found only this function useful for the task.

Syntax:

mixed preg_replace_callback ( mixed $pattern , callback $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )

Example:

Find and replace all links in an Input text/string using Regex:

The text/string can come from a file or you got from user input. Source can be different. We want to find all links and replace it with the text inside link. Suppose this is a link:  <a href="http://www.satya-weblog.com">Web Scripting</a>. We want to strip everything except "Web Scripting". Normally for the exact scenario, you can use strip_tags() function. Here we will do the same thing using preg_replace_callback() regular expression function. The example will achieve multiple find and replace of text links.

PHP code:

<?php
$cleanInputText = '';
function findAndReplace($arr) {
	global $cleanInputText;
	static $ct = 0;
	$ct++;
	//print_r($arr);
	$cleanInputText[] =  $arr[0];
	return $arr[1];
}
$inputText = <<<EOD
<ul id="menus">
		<li><a href="/tag/php"  style="padding-left:5px"> PHP </a> </li>
		 <li> <a href="/tag/javascript"> Javascript </a> </li>
		 <li> <a href="/tag/css"> CSS </a> </li>
		 <li> <a href="/tag/linux"> Linux </a> </li>
		 <li> <a href="/tag/wordpress"> WordPress </a> </li>
		 <li> <a href="/tag/seo"> SEO </a> </li>
		 <li> <a href="/tag/tips-tricks"> Tips/Tricks </a> </li>
		 		<li><a class="lastmenu" href="javascript:void(0);"></a></li>
	</ul>
	Testing testing
EOD;
$modifiedText = preg_replace_callback('@<a(?:.*)>(.*)</a>@isU', 'findAndReplace', $inputText);
//Output:
// Our modified text
echo $modifiedText;
// Links we got in the process
echo (implode(',', $cleanInputText));
?>

Output:

Our modified text:<br>
<ul id="menus">
		<li> PHP  </li>
		 <li>  Javascript  </li>
		 <li>  CSS  </li>
		 <li>  Linux  </li>
		 <li>  WordPress  </li>
		 <li>  SEO  </li>
		 <li>  Tips/Tricks  </li>
		 		<li></li>
	</ul>
	Testing testing
Links we got in the process: <br><a href="/tag/php"  style="padding-left:5px"> PHP </a>,
<a href="/tag/javascript"> Javascript </a>,
<a href="/tag/css"> CSS </a>,
<a href="/tag/linux"> Linux </a>,
<a href="/tag/wordpress"> WordPress </a>,
<a href="/tag/seo"> SEO </a>,
<a href="/tag/tips-tricks"> Tips/Tricks </a>,
<a class="lastmenu" href="javascript:void(0);"></a>

The method discussed here can achieve varieties of task of searching and replacing word/text in any string given. Just play with it for some time.

Comments are open for an year period. Please, write here on Facebook page.