正则表达式替换特定字符串和onclick事件周围的标记

时间:2017-03-17 13:02:32

标签: php regex

这是我的字符串

<p>Testing is a key element to any application. 
<a href="software-testing.html" onclick="ga('send', 'event', 'internal', 'Node.js', 'Node.js');"> Link1 </a> is called Jasmine. In early 2000, there was a framework for testing  JavaScript applications called JsUnit. Later this framework got upgraded and is now known as jasmine. </p>
<p>Jasmine helps in automated unit <a href="software-testing.html"> Link2 </a>

我想将唯一标记移到&#34; onclick事件&#34;和&#34; software-testing.html &#34;确切的单词与替换匹配。

我尝试了两个代码

 1) <a(.*?)software-testing.html(.*?)<\/a>
 2) \s*<a(.*?)software-testing.html|onclick="[^"]*"[^>]*>((?:(?!</a>).)*)</a>\s*

但在我的情况下,链接1和链接2被替换。

这不起作用。我已经搜索了几天并尝试了许多其他选项,但从未设法让它按预期工作。

仅替换Link1而不替换Link2。

请帮助我。

2 个答案:

答案 0 :(得分:1)

您可以使用以下正则表达式 ...

来完成此操作
<.*?\shref="software-testing.html"\sonclick.*?<\/.*?>

参见 regex demo / explanation

PHP demo

$regex = '/<.*?\shref="software-testing.html"\sonclick.*?<\/.*?>/';
$str = '<p>Testing is a key element to any application. 
<a href="software-testing.html" onclick="ga(\'send\', \'event\', \'internal\', \'Node.js\', \'Node.js\');"> Link1 </a> is called Jasmine. In early 2000, there was a framework for testing  JavaScript applications called JsUnit. Later this framework got upgraded and is now known as jasmine. </p>
<p>Jasmine helps in automated unit <a href="software-testing.html"> Link2 </a>';
$subst = 'Show me \$1';
$result = preg_replace($regex, $subst, $str);
echo $result;

答案 1 :(得分:0)

另一种方法是使用simplehtmldom

<?php
require 'simple_html_dom.php';
$htmlString='<p>Testing is a key element to any application. 
<a href="software-testing.html" onclick="ga(\'send\', \'event\', \'internal\', \'Node.js\', \'Node.js\');"> Link1 </a> is called Jasmine. In early 2000, there was a framework for testing  JavaScript applications called JsUnit. Later this framework got upgraded and is now known as jasmine. </p>
<p>Jasmine helps in automated unit <a href="software-testing.html"> Link2 </a>';
$html = new simple_html_dom();
$html->load($htmlString);
$tags = $html->find('a[onclick][href=software-testing.html]');
$tags[0]->outertext=$tags[0]->innertext;
echo $html;