Jump to content

[SOLVED] preg_replace is messing header


asmith

Recommended Posts

I'm using ob_start, I get all the page output, I use preg_replace for bold some words .

 

The Problem I'm facing is, If a word is in the site header, it make that bold too and mess up with the page. Is there anyway I could tell preg_replace to skip what is between <head> tags ?

 

 

Link to comment
https://forums.phpfreaks.com/topic/127021-solved-preg_replace-is-messing-header/
Share on other sites

I think the problem is three fold..

 

1) The first line in your code has 'get_ob_content()', which is incorrect. It is ob_get_contents().

2) You 'might' have to rethink what it is your are going to apply your regex to.

3) Your current pattern utilizes alternation, meaning when it finds the first word match, the < b >$0< /b > will be executed, and then that's it (because the condition has been met).

 

While I cannot help out with point number 2, here is what I came up with for number 3 (and also the correct function name from the error in number 1 at the same time):

$string = ob_get_contents();
echo preg_replace(array('#\bword1\b#i','#\bword2\b#i','#\bword3\b#i','#\bword4\b#i'), '<b>$0</b>', $string);

 

This will apply the changes to all those keywords (or whatever you may replace them with in the array).

So this is hopefully part of the solution. But applying this pattern to 'ob_get_contents()' might not work for you.. so you might need to rethink what you are going to need to apply this to to work (in other words, how to not apply it to your header stuff).

 

Try the new snippet out first.. but I do think there still might be some issues.

 

Cheers,

 

NRG

firstly thanks nrg for the replay. I admire your "wanting" to answer a question.

 

However you are not close to my problem.

 

Sorry my bad to typed the ob_get_content wrong.

I got the function running fine, the only problem is it is doing my header too .

The reason I'm imploding an array there is those words in array can be different or the number of the words is changeable.

 

Last night I was coding too much and I had brain lag ;)

 

the answer is simple, I find the <body> with strpos and catch other content with substr.

 

Cheers

 

 

$string = get_ob_content();
$words_to_bold = array("word1","word2","word3","word4");
echo preg_replace('~('.implode('|', $words_to_bold).')~','<b>$0</b>',$string);}

 

do it step by step, ie KISS

foreach($words_to_bold as $k){ 
   echo str_replace( .....);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.