How to replace a tag in php

藏色散人
Release: 2023-03-05 12:54:02
Original
2603 people have browsed it

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.

How to replace a tag in php

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 = &#39;/href=(\"|\&#39;)(.*?)(\"|\&#39;)/i&#39;;
  $replacestr = &#39;href="#"&#39;;
  $res = preg_replace($preg, $replacestr, $str);
  return $res;
}
// 获取字符串中的所有a标签
function from_str_get_a($str){
    $preg = &#39;/<a .*?>/i&#39;;
    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);
?>
Copy after login

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:
How to replace a tag in php
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!

Related labels:
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