Home > Article > Backend Development > How to replace all strings with php regular expression
How to implement regular php replacement of all strings: first use the preg_match() function to match all strings; then traverse the array; then use the strpos function to calculate the position; finally use the substr_replace function to replace the string at the specified position. .
Recommended: "PHP Video Tutorial"
php Replace multiple different characters in a string
There are two functions that can replace strings
The idea is to use the preg_match() function to first match all strings, traverse the array strpos(), calculate the position, and use substr_replace() to replace the specified position. String.
For example: replace all a tags in an html page
function getAarr($str){ //拿出网页中所有a标签放到数组 $reg1="/<a[\s\S]*?>[\s\S]*?<\/a>/"; $aarray = array();//这个存放的就是正则匹配出来的所有《a》标签数组 preg_match_all($reg1,$str,$aarray); return $aarray[0]; } function replace($sou_str,$urls){ $arr_a = getAarr($sou_str); shuffle($urls); foreach($arr_a as $i=> $one){ $begin = strpos($sou_str,$one);//开始位置 $length = strlen($one);//字符串长度 if(!isset($urls[$i])){ $urls[$i]['name'] = str_replace(" ","",strip_tags($one)); $urls[$i]['url'] = "./?".$urls[$i]['name']; $urls[$i] = "<a target='_blank' href='".$urls[$i]['url']."' title='".$urls[$i]['name']."'>".$urls[$i]['name']."</a>"; }else{ $urls[$i] = "<a target='_blank' href='".$urls[$i]['url']."' title='".$urls[$i]['name']."'>".$urls[$i]['name']."</a>"; } if ($begin!==false){ $sou_str = substr_replace($sou_str,$urls[$i],$begin,$length); } } return $sou_str; }
The above is the detailed content of How to replace all strings with php regular expression. For more information, please follow other related articles on the PHP Chinese website!