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
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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