Jump to content


Photo

*solved* replace first instance of string without affecting case???


  • Please log in to reply
2 replies to this topic

#1 bcamp1973

bcamp1973
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 30 October 2006 - 11:36 PM

ok, i've been messing with str_replace(), preg_replace() and ereg_replace() and i'm not quite getting the results i want. Most likely because regular expressions mess with my head. I want to parse a string, and replace the first instance of select words (in an array) with the same word (case unchanged) but wrapped in a tag etc.

So, i want the following...

<p>A doctor may need to review your records from your previous doctor's office</p>

with...

<p>A <acronym title="A guy in a white coat">doctor</acronym> may need to review your records from your previous doctor's office</p>

I'm having a couple problems. 1) how do i maintain the case of the word replaced?  My array of terms are all capitalized, but the term to be replaced may or may not be.  2) how do i only replace the first instance?

Finally, if someone feels up for giving me a dumbed down difference between ereg_replace and preg_replace i'd appreciate it. The PHP manual doesn't spell it out clearly enough for me :P

#2 Nicklas

Nicklas
  • Members
  • PipPipPip
  • Advanced Member
  • 111 posts
  • Locationwww.nswardh.com

Posted 31 October 2006 - 12:02 AM

You could do something like this:
<?php

$replace = array(
				"'\b(doctor)\b'is",
				"'\b(records)\b'is"
				);

$with = array(
			'<acronym title="A guy in a white coat">\\1</acronym>',
			'<acronym title="Guinnes world of records">\\1</acronym>'
			);

$string = "<p>A doctor may need to review your records from your previous doctor's office</p>";

echo preg_replace($replace, $with, $string, 1);

?>


#3 bcamp1973

bcamp1973
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 31 October 2006 - 12:10 AM

it's working perfectly, thanks!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users