在$variable中,我有一个html代码,读起来像:`
<tag>Lots of Text Here - More Phrases Here</tag>.
我希望能够str_replace两个标签之间的字符串
<tag> string </tag>
我想让新代码读:
<tag><a href="Lots">Lots</a> <a href="of">of</a>
<a href="text">Text</a> <a href="here">Here</a> -
<a href="@morephraseshere">@MorePhrasesHere</a></tag>
我知道这可能会让str_replace一下子变得很难,但如果你至少能让"这里有很多文本"成为链接,或者让@MorePhrasesHere成为链接,那就太棒了。
或者,你能最接近一个完整的解决方案也会很棒。
$variable中的文本字符串对于每个条目都会发生变化。如果您不能在str_replace中执行$variable的preg_match或str_explode解决方案,那么它也会非常棒。
谢谢!
编辑:目标是将第一个字符串中的每个单词变成#标签,将第二个字符串中每个单词变成@username。服务器知道如何为这两种类型的链接返回有效响应。
以下是我如何使用preg_match
执行此操作,http://php.net/manual/en/function.preg-match.php..
表示任何字符,*
是一个量化器,表示前一个字符出现0次或更多次。由于是.
,我们允许一切。?
不一致,因此它正在寻找-
的第一次出现,然后我们再次提取其他所有内容,直到</tag>
。
<?php
preg_match('~<tag>(.*?)-(.*?)</tag>~', '<tag>Lots of Text Here - More Phrases Here</tag>', $found);
echo '<a href="#' . urlencode(trim($found[1])) . '">' . trim($found[1]) . '</a>' . "'n";
echo '<a href="@' . urlencode(trim($found[2])) . '">' . trim($found[2]) . '">' . '</a>' . "'n";
?>
输出:
<a href="#Lots+of+Text+Here">Lots of Text Here</a>
<a href="@More+Phrases+Here">More Phrases Here"></a>
你应该开始学习元字符和量词。这将帮助您在将来编写自己的正则表达式。你应该浏览这个网站;它有点长,但也有很多信息,http://www.regular-expressions.info/php.html
获取此代码。没有什么可以解释
$title = '<tag>Lots of Text Here - More Phrases Here</tag>';
preg_match('/<tag>'s*(.+)'s+-'s+(.+)'s*<'/tag>/', $title, $matches);
$res = '<tag>';
$words = explode(' ', $matches[1]);
foreach ($words as $word)
$res .= '<a href="#'.$word.'">'.$word.'</a> ';
$after = str_replace(' ','', $matches[2]);
$res .= '<a href="@'.$after.'">@'.$after.'</a></tag>';
echo $res;