Jump to content

Preg Replace Help!


Oaryx

Recommended Posts

Hello,

 

My knowledge of regular expressions is pretty limited; and I have to get something done very soon using them. I have a variable called $searchString. I've searched for strings in a database which have text that matches that provided string. I'd like to add <span class="highlight"> before the search string and close the span right after.

 

Right now I have:

preg_replace("|($searchWord)|Ui" , "<span class=\"highlight\">$searchString</span>" , $string);

 

So, if the user searches for pAnTs, they will see:

 

"I like to wear <span class="highlight>pAnTs</span> all day" instead of "I like to wear <span class="highlight>pants</span> all day", which is the exact string in the database with the proper cases.

 

I want to simply replace the beginning and end of the search string with the highlight class, instead of all of it so that it looks exactly like it does in the database.

 

Any help would be much appreciated. Sorry if this is a complete noob question (but unfortunately, I kind of am one).

Link to comment
https://forums.phpfreaks.com/topic/269072-preg-replace-help/
Share on other sites

As a little aside, I'd use some other delimiters than pipes. Forward slashes or hash signs (#) are the most common ones. Pipes does have a semantic meaning in RegExp, after all, and using them as delimiters will cause problems if you ever wanted to search for two alternative words.

Link to comment
https://forums.phpfreaks.com/topic/269072-preg-replace-help/#findComment-1382671
Share on other sites

The problem with that is that curly brackets also have a semantic meaning in Regular Expressions, same with square brackets and normal parentheses (both of which can also be used as delimiters). Which is why I recommend using one of the two "standard" delimiters, even though there's a lot of other characters that can be used for delimiters.

Link to comment
https://forums.phpfreaks.com/topic/269072-preg-replace-help/#findComment-1382688
Share on other sites

As a little aside, I'd use some other delimiters than pipes.

 

And I'd butt out of the thread if not helping with the question posed. (Except for now.)

 

I'll definitely look into not using pipes.

 

It's not about "not using pipes", but rather being aware that sometimes it pays to put some thought into the delimiter character(s) being used if they are also used within the pattern.

Link to comment
https://forums.phpfreaks.com/topic/269072-preg-replace-help/#findComment-1382705
Share on other sites

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.