Чтобы найти все хэш-теги, используйте regex и preg_match_all ()
, и сделайте замену preg_replace ()
:
$regex = '/(#[A-Za-z-]+)/';
preg_match_all( $regex, $string, $matches);
$string_f = preg_replace( $regex, "$1", $string);
Тогда все признаки находятся во множестве в $matches [1]
:
$tags_array = $matches[1];
Затем новообращенный это к разделенному пробелом списку с интегрируйтесь ()
и array_unique ()
:
$tags = implode( ' ', array_unique( $tags_array));
И вы сделаны. Вы видите от этот демонстрационный пример тот $tags
и $string_f
:
"#hashtag #another #example"
"Hello. This is a #hashtag and this is yet another #hashtag. This is #another #example."
Для других знаков в хэш-теге (например, цифры), изменяют $regex
соответственно.
Edit: However, this can be improved in efficiency if you use preg_replace_callback()
and a closure so you only have to execute the regex once, like so:
$tags_array = array();
$string_f = preg_replace_callback( '/(#[A-Za-z-]+)/', function( $match) use( &$tags_array) {
$tags_array[] = $match[1];
return "" . $match[1] . "";
}, $string);
$tags = implode( ' ', array_unique( $tags_array));