Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub-string splitting - PHP

Tags:

substring

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.

like image 514
Ryan Avatar asked Jun 18 '26 21:06

Ryan


1 Answers

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.

like image 80
Barmar Avatar answered Jun 21 '26 11:06

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!