-1

I previously asked this question entirely wrong so making another attempt. Don't hang me!

Text is retrieved from a file.

Blah blah blah blah<br />blah blah blah<br />#text to be a color<br />blah blah

I have code that preg_replace the word connected to the symbol but I can not get the regex to go from the symbol to the end of the line aka from <br /># to before <br />

Here is my code for the symbol word

$line = preg_replace('/(?<!\w)#([0-9a-zA-Z]+)/m', '<span class='alt'>#$1</span>', $line);

After searching, basically what I want to regex is like the greentext thing on 4chan but I can not find code examples of replacing the entire line IF ONLY a new line begins with the symbol.

Vimmy
  • 81
  • 1
  • 7

2 Answers2

1

There are a couple of things. I've made the regex specify the <br /> as the delimiters and you also have to escape some of the quotes in your replacement string...

$line = preg_replace('/<br \/>#([^<]*)/m', '<span class=\'alt\'>#$1</span>', $line);

With...

Blah blah blah blah<br />blah blah blah<br />#text to be a color<br />#blah blah<br />

you end up with

Blah blah blah blah<br />blah blah blah<span class='alt'>#text to be a color</span><span class='alt'>#blah blah</span><br />
Nigel Ren
  • 51,875
  • 11
  • 34
  • 49
  • Oops, actually in my existing code I have double quotes for the class which works. Don't know why I typed single above. As for your code.. does this go to the end of the line and stop before the next break? – Vimmy Mar 17 '20 at 20:39
  • I've added some example output – Nigel Ren Mar 17 '20 at 20:40
  • I added br / to the output to replace the break which then your code did go end of line which is great. The issue that just became apparent is "what if the text BEGINS WITH the symbol" which then there will not be a br before it. Probably just easier to do two versions one with and then run one without or vice versa. Hey thanks for the regex! – Vimmy Mar 17 '20 at 20:47
  • Actually I will ask you, how would you go about IF the FIRST character is the symbol. Bcz if I remove the br / in the regex then it will replace ANYWHERE in the string as opposed to JUST the first line – Vimmy Mar 17 '20 at 20:49
  • You can make the opening tag optional by changing it to `'/(?:
    )?#([^
    – Nigel Ren Mar 17 '20 at 20:50
  • That ended up replacing it anywhere instead of just the very first. I am thinking the option is to IF the first character in the string is # then preg_replace and limit it to 1 – Vimmy Mar 17 '20 at 20:55
  • An alternative is `(^|
    )#([^`
    – Nigel Ren Mar 17 '20 at 21:10
0

Explanation

You want to use PHP's strstr function to find the text within the string. From your example of $line, it will find the first occurrence of your text and display the remainder of the string.


Code

$line = strstr($line, '<br />#');
$line = preg_replace('/(?<!\w)#([0-9a-zA-Z]+)/m', '<span class='alt'>#$1</span>', $line);
Mech
  • 3,611
  • 1
  • 12
  • 25