简体   繁体   English

php用正则表达式替换标签

[英]php replace tag with regex

I searched in many forums about replacing the text between a tag, but all I get is how to remove text between tags etc. That's not what I'm looking for.我在许多论坛中搜索了关于替换标签之间的文本,但我得到的只是如何删除标签之间的文本等。这不是我要找的。 Here is a little example so you can understand what I'm talking about.这是一个小例子,所以你可以理解我在说什么。 I want to replace:我想更换:

<form action="link1" method="post" name="form" id="form">

What I want to do is to get rid of this form and changes it to:我想要做的是摆脱这种形式并将其更改为:

<form action="link2" ....> 

Now, my problem is not about replacing but with choosing form tag.现在,我的问题不是替换而是选择表单标签。
I hope you understand me.我希望你能理解我。

You have structured data (html are structured data), so use this structure.您有结构化数据(html 是结构化数据),因此请使用此结构。 What you want to do is to change an attribute value, it's easy with DOMDocument:您要做的是更改属性值,使用 DOMDocument 很容易:

$dom = new DOMDocument;
$dom->loadHTML($yourHTML);

$formTagList = $dom->getElementsByTagName('form');

foreach ($formTagList as $formNode) {
    if ($formNode->hasAttribute('action') && $formNode->getAttribute('action') === 'link1')
        $formNode->setAttribute('action', 'link2');
}

$result = $dom->saveHTML();

If you want to use a regular expression, then you should use preg_replace - http://php.net/manual/en/function.preg-replace.php .如果你想使用正则表达式,那么你应该使用 preg_replace - http://php.net/manual/en/function.preg-replace.php If you have a sample document, and the output you want, that would help too.如果您有示例文档和所需的输出,那也会有帮助。

I'm not sure if I understood your question, but basing in your sample it's pretty simple.我不确定我是否理解您的问题,但根据您的示例,这非常简单。 You can use this regex:您可以使用此正则表达式:

<form.*?>

And the replacement string和替换字符串

<form action="link2" ....> 

Working demo工作演示

Php code php代码

$re = "/<form.*?>/"; 
$str = "<form action=\"link1\" method=\"post\" name=\"form\" id=\"form\"></form>"; 
$subst = "<form action=\"link2\" ....>"; 

$result = preg_replace($re, $subst, $str);

//result:
//     <form action="link2" ....></form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM