2012-07-16 124 views
0

我快到了!PHP preg_replace:如果超链接包含“youtube.com”,则需要修改超链接文本

这是我想调整的字符串,以及我的preg_replace尝试。

$description_string = '<p>Here is the test link: <a href="http://www.youtube.com/watch?v=2MFn8L9tIrg" target="_blank">“Man or Muppet”</a> with other text afterwards.</p>';

$description = preg_replace('/(<a[^>]+youtube[^>]*>)+[^"]*(<\/a>)+/', '$0Watch This Video$2', $description);

我得到的结果是不正确的:

下面是测试环节:“人或布偶”观看这部影片与其他文本之后。

任何帮助将不胜感激!谢谢!

+2

使用正则表达式停止,开始使用'DOMDocument'。 – Jon 2012-07-16 19:45:27

+0

同意@Jon,这不是一个正则表达式候选人,您应该使用文档分析来代替...... – 2012-07-16 19:50:06

+0

为什么DOMDocument在这种情况下更好? – handstand 2012-07-16 19:55:12

回答

0

那么,不知道你是否试图在那里得到实际的标题。但这里是我想出了:

<?php 
$description_string = '<p>Here is the test link: <a href="http://www.youtube.com/watch?v=2MFn8L9tIrg" target="_blank">\'Man or Muppet\'</a> with other text afterwards.</p>'; 

$description = preg_replace('/(<a[^>]+youtube[^>]*>)+[^"]*(<\/a>)+/', '$1Watch This Video$2', $description_string); 

echo $description; 
?> 

结果:

<p>Here is the test link: <a href="http://www.youtube.com/watch?v=2MFn8L9tIrg" target="_blank">Watch This Video</a> with other text afterwards.</p> 

你最大的问题是在标题为引号(“),这是切断锚标签在使用。 $ 0也是不正确的。你需要使用$ 1

这可能不是正是你需要的,但它给你一个快速的猴子补丁。

+0

非常有帮助,谢谢! – handstand 2012-07-17 21:34:23