0

#123我想以 to 的形式转换字符串的子字符串<a href='show.php?id=123'>#123</a>。所以让他们链接。

所以字符串"take a look at #42"转换为"take a look at <a href='show.php?id=42'>#42</a>".

php有内置函数吗?

谢谢

4

3 回答 3

1
$pattern = '/([^#]+)(#[\d]+)([^#]+)/';
$str = 'Take a look at #42';
if (preg_match($pattern, $str, $matches)){
    echo $matches[1]."<a href='show.php?id=".substr($matches[2], 1)."'>". $matches[2].'</a>'.$matches[3];
}

这输出:

Take a look at <a href="show.php?id=42">#42</a>
于 2013-07-10T10:43:33.670 回答
1
<?php

$string="take a look at #42";
if (preg_match('/#[0-9]+/', $string, $matches)){
echo "<a href='show.php?id=".substr($matches[0], 1)."'>". substr($matches[0], 1).'</a>';

}

?> 
于 2013-07-10T10:50:09.033 回答
1

用于preg_replace_callback()执行替换:

echo preg_replace_callback('/#(\w+)/', function($match) {
    return sprintf('<a href="show.php?id=%s">%s</a>',
        $match[1],
        '#' . $match[1]
    );
}, 'take a look at #42');
// look at <a href="show.php?id=42">#42</a>

虽然这里没有严格要求,但请确保正确转义 HTML :)

也可以看看:urlencode() htmlspecialchars()

于 2013-07-10T10:55:46.490 回答