How to replace all strings with php regular expression

藏色散人
Release: 2023-03-07 16:16:02
Original
2870 people have browsed it

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. .

How to replace all strings with php regular expression

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][&#39;name&#39;] = str_replace(" ","",strip_tags($one));
            $urls[$i][&#39;url&#39;] = "./?".$urls[$i][&#39;name&#39;];
            $urls[$i] = "<a target=&#39;_blank&#39; href=&#39;".$urls[$i][&#39;url&#39;]."&#39; title=&#39;".$urls[$i][&#39;name&#39;]."&#39;>".$urls[$i][&#39;name&#39;]."</a>";
        }else{
            $urls[$i] = "<a target=&#39;_blank&#39; href=&#39;".$urls[$i][&#39;url&#39;]."&#39; title=&#39;".$urls[$i][&#39;name&#39;]."&#39;>".$urls[$i][&#39;name&#39;]."</a>";
        }
        if ($begin!==false){
            $sou_str = substr_replace($sou_str,$urls[$i],$begin,$length);
        }
    }
    return $sou_str;
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template