Jump to content

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


bcamp1973

Recommended Posts

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

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

with...

[code]<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>[/code]

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
You could do something like this:
[code]<?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);

?>[/code]

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.