Php- Replace all found items in a string



You may need to replace all occurrences in a string not just the first item found by ‘str_replace’ function. Here we have designed a function to act al a replace_all button in notepad.

function replaceall($str,$old,$new,$offset = 0){
	$pos	= strpos($str,$old,$offset);
	$str	= str_replace($old,$new,$str);
 	return $str;
}

 

You can edit the offset, which determines the starting point in the function. so the all $old matches will be replaced by $new with this function. Hope to be useful!



Be the first to comment

Leave a Reply

Your email address will not be published.


*