PHP str_replace <tag>东西 - 东西</tag>到<a href="stuff">Stuff</a> <a href="things">Things?

时间:2015-05-15 19:10:53

标签: php regex preg-match str-replace

In $variable I have html code which reads like:`

<tag>Lots of Text Here - More Phrases Here</tag>.

I'd like to be able to str_replace the string in between the 2 tags

<tag> string </tag>

I want the new code to read:

<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>

I know this might be a lot to str_replace all at once, but if you can at least get either the "Lots of Text Here" to become links, or if you can get the @MorePhrasesHere to become a link it would be amazing.

Or the closest you can get to a full solution would be fantastic as well.

The string of text in $variable changes for each entry. A preg_match or str_explode solution for $variable would be amazing as well if you can't do it in str_replace.

Thank you!

Edit: The objective is to turn every word in the first string into a #hashtag, and every word in the second string into a @username. The server knows how to return valid responses for both types of links.

2 个答案:

答案 0 :(得分:1)

以下是我preg_matchhttp://php.net/manual/en/function.preg-match.php的方式。 .表示任何字符,*是一个量化符,表示前一个字符出现0次或更多次。因为.我们允许一切。 ? de-greedifys正在寻找-的第一次出现,然后我们将其他所有内容再次提取到</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

答案 1 :(得分:0)

拿这个代码。没有什么可以解释的

$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;