如何从变量中删除文本? (PHP)

时间:2010-04-07 08:20:30

标签: php regex

我有一个变量$link_item,它与echo一起使用,并提供类似

的字符串
<span class="name">Google</span>http://google.com

如何从字符串中删除“ <span class="name">Google</span> ”?

它应该只提供“http://google.com”。

听说可以使用regex()完成,请提供帮助。

5 个答案:

答案 0 :(得分:3)

没有正则表达式:

echo substr($link_item, stripos($link_item, 'http:'))

但这只适用于第一部分(即<span class="name">Google</span>)从不包含http:的情况。如果你能保证这一点:在这里你去:))

参考:substrstripos

<强>更新

正如@Gordon在评论中指出的那样,我的代码与strstr()的代码一样。我只是把它放在这里以防万一没有阅读评论:

echo strstr($link_item, 'http://');

答案 1 :(得分:3)

$string = '<span class="name">Google</span>http://google.com';
$pieces = explode("</span>",$string);
//In case there is more than one span before the URL
echo $pieces[count($pieces) -1];

答案 2 :(得分:1)

解决:

$contents = '<span class="name">Google</span>http://google.com';
$new_text = preg_replace('/<span[^>]*>([\s\S]*?)<\/span[^>]*>/', '', $contents);
echo $new_text;

// outputs -> http://google.com

答案 3 :(得分:0)

不要使用正则表达式。使用HTML parser仅从中提取所需的文本。

答案 4 :(得分:0)

自己制作

$link_item_url = preg_replace('@<span[^>]*?>.*?</span>@si', '', $link_item);

这将从变量<span + something + </span>中删除所有$link_item

谢谢大家。