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

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

  •  26-06-2022
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top