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

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

  •  26-06-2022
  •  | 
  •  

Frage

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

War es hilfreich?

Lösung

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>.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top