How do i turn all # tags into a hyperlink?
If this script detects then displays all # tags, how do i change it so it makes t开发者_运维问答hem all a hyper link? Basically putting an <a href="#">
infront of it and a </a>
behind
$str = <<<STR
this is a string
with a #tag and
another #hello one
STR;
$matches = array();
if (preg_match_all('/#([^\s]+)/', $str, $matches)) {
var_dump($matches[1]);
}
It sounds like you want to do this:
$str = <<<STR
this is a string
with a #tag and
another #hello one
STR;
$matches = array();
if (preg_match_all('/#([^\s]+)/', $str, $matches)) {
// Get rid of the full matches
array_shift($matches);
// Now get the first array element which are the actual captured matches
list($matches) = $matches;
foreach($matches as $match) {
echo "<a href='#'>{$match}</a>\n";
}
}
Output:
$ php test.php
<a href='#'>tag</a>
<a href='#'>hello</a>
You can use back-references, and preg_replace
to do this.
echo preg_replace('/#([^\s]+)/', '<a href="#">$1</a>', $str);
Output:
this is a string
with a <a href="#">tag</a> and
another <a href="#">hello</a> one
If you want the #
to be part of the link, simply change the regex to /(#[^\s]+)/
.
Demo: http://ideone.com/T06HQ
sed 's/#/URL/' myhtmlfile.html
Where URL is the url you want to replace the # with.
精彩评论