Check string for # symbol and the immediately following characters, then colour that string

StackOverflow https://stackoverflow.com/questions/18552216

  •  26-06-2022
  •  | 
  •  

Question

How can I check a string for a hash tag, and its connected characters?

Example: This is my sample string #example of what I mean.

*I want to extract this:* #example

Then I want to change the text colour of that found string

Was it helpful?

Solution

This will surround the hashtag with a span element.

$sampleText = 'This is my sample string #example of what I mean. Here is another #test.';
$pattern = '/#[a-zA-Z0-9]*/';
$replacement = '<span class="otherColor">$0</span>';
$updatedText = preg_replace($pattern, $replacement ,$sampleText);
print_r($updatedText);

Output:

This is my sample string <span class="otherColor">#example</span> of what I mean. Here is another <span class="otherColor">#test</span>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top