我有一个包含文本的字符串,在一些地方会有一个twitter风格的标签。我想找到它们并创建一个单独的变量,其中所有这些变量都由空格分隔。我还想将原始字符串中的所有标签转换为链接。示例:
$string = "Hello. This is a #hashtag and this is yet another #hashtag. This is #another #example."after函数:
$string_f = "Hello this is a <a href='#'>#hashtag</a> and this is yet another <a href='#'>#hashtag</a>. This is <a href='#'>another</a> <a href='#'>example</a>";
$tags = '#hashtag #another #example';发布于 2013-01-09 22:26:46
要查找所有散列标记,请使用正则表达式和preg_match_all(),并使用preg_replace()进行替换
$regex = '/(#[A-Za-z-]+)/';
preg_match_all( $regex, $string, $matches);
$string_f = preg_replace( $regex, "<a href='#'>$1</a>", $string);然后所有标签都在$matches[1]中的一个数组中
$tags_array = $matches[1];然后,使用implode()和array_unique()将其转换为空格分隔的列表
$tags = implode( ' ', array_unique( $tags_array));你就完事了。您可以从this demo中看到$tags和$string_f是:
"#hashtag #another #example"
"Hello. This is a <a href='#'>#hashtag</a> and this is yet another <a href='#'>#hashtag</a>. This is <a href='#'>#another</a> <a href='#'>#example</a>."对于哈希标记中的其他字符(例如数字),请相应地修改$regex。
编辑:但是,如果您使用preg_replace_callback()和闭包,则可以提高效率,这样您只需执行一次正则表达式,如下所示:
$tags_array = array();
$string_f = preg_replace_callback( '/(#[A-Za-z-]+)/', function( $match) use( &$tags_array) {
$tags_array[] = $match[1];
return "<a href='#'>" . $match[1] . "</a>";
}, $string);
$tags = implode( ' ', array_unique( $tags_array));发布于 2013-01-09 22:26:26
来个漂亮的正则表达式怎么样?
preg_match_all("/#[\w\d]+/", $string, $matches, PREG_SET_ORDER);
unset($matches[0]);
$tags = implode(" ", $matches);https://stackoverflow.com/questions/14237317
复制相似问题