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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
