子字符串拆分 - PHP

So, I guess that this is a pretty simple concept, but I am unsure as to how I would achieve my intended result. What I am wanting, is for words which start with the '@' symbol, to be outputted with a <span> encasing them.

Let's say that the following is the whole string:

Mark wants the new app to be released on Friday, but some assets need refining so that they fit the theme @design_team.

How would I capture the...

@design_team

...sub-string, bearing in mind that characters other than an underscore should not be accounted for in the sub-string, to help keep the format.

Please let me know if this is possible with PHP, and if so, how.

Use preg_replace:

$string = preg_replace('/@\w+/', '<span>$0</span>', $string);

\w matches word characters (letters, numbers, underscore), + makes it match a sequence of them. And in the replacement string $0 gets the matching substring.

Use preg_match()

$str = "Mark wants the new app to be released on Friday, but some assets need refining so that they fit the theme @design_team.";
preg_match('/\@[a-zA-Z_]+/', $str, $matches);
print_r($matches);

The output is

Array
(
    [0] => @design_team
)

You can use regular expressions to achieve this. Here's an example:

$string = 'Hello @php and @regex!';

$matches = [];
preg_match_all('/@(\w+)/', $string, $matches);

var_dump($matches);

Output:

array(2) {
  [0] =>
  array(2) {
    [0] =>
    string(4) "@php"
    [1] =>
    string(6) "@regex"
  }
  [1] =>
  array(2) {
    [0] =>
    string(3) "php"
    [1] =>
    string(5) "regex"
  }
}

Further reading: preg_match_all.

I think it would be easier to use a regular expression if you have multiple @words per string:

$string = '@Mark wants the new app to be released @Friday, but it needs some @refining';
$didMatch = preg_match_all('/(@[^\W]+)/', $string, $matches);

if($didMatch) { 
    echo "There were " . count($matches[0]) . " matches: <br />";
    print_r($matches[0]);
} else { 
    echo "No @words in string!
";
}