How to replace a tag in php: first open the corresponding PHP file; then define a "from_str_get_a" method; then search and replace the string through the "str_replace" method.
Recommendation: "PHP Video Tutorial"
The code a link that I picked up when imitating the website always points to In other places, it would be tiring to change one by one. When displaying, it would jump randomly when you click on it, which is very annoying, so I wanted to use PHP to write a code that can change the href attribute of a link. The code is as follows:
<?php // 替换a标签中的href属性值 function a_replace_href($str) { $preg = '/href=(\"|\')(.*?)(\"|\')/i'; $replacestr = 'href="#"'; $res = preg_replace($preg, $replacestr, $str); return $res; } // 获取字符串中的所有a标签 function from_str_get_a($str){ $preg = '/<a .*?>/i'; preg_match_all($preg, $str, $imgArr); return $imgArr[0]; } $str = file_get_contents("index.html"); $data = from_str_get_a($str);//获取字符串中的a标签 $data1 = a_replace_href($data);//替换后应该显示的a标签 $res = $str; // 反复对字符串进行查找替换 foreach ($data as $key => $value) { $res = str_replace($value,$data1[$key],$res,$i); } // 另存文件 file_put_contents("index1.html",$res); ?>
The principle is to use regular matching and then replace. If you have better ideas or optimizations, please leave a comment and share your experience!
The test results are as follows:
Source file code:
Replaced file code:
The above is the detailed content of How to replace a tag in php. For more information, please follow other related articles on the PHP Chinese website!