Jump to content

replace single words in php


e111982

Recommended Posts

Hi. I have got a problem. I have a string like:

 

$old="apple";

$new="lemon";

 

$str="I have got one green apple, two yellow apples, oranges and grapes.";

 

I want an output as :

 

I have got one green lemon,two yellow apples, oranges and grapes.

 

However str_replace replaces all occurrences. I need only words to be replaced. Thanks.

Link to comment
https://forums.phpfreaks.com/topic/182508-replace-single-words-in-php/
Share on other sites

Use preg_replace it allows you to add a limit to the replacement.

 

<?php
$old ="#apple#i";
$new ="lemon";

$str ="I have got one green apple, two yellow apples, oranges and grapes.";
$str = preg_replace($old, $new, $str, 1);

echo 'Output: ' . $str;
?>

 

Output: I have got one green lemon, two yellow apples, oranges and grapes.

 

You can use preg_replace to do this. Example:

 

$old="apple";
$new="lemon";
$str="I have got one green apple, two yellow apples, oranges and grapes.";
echo preg_replace("~\b$old\b~", $new, $str);

 

Edit: Angy-H's solution will only work if the occurrence of the string that you want to replace is the first one in the string.

Can you explain what the word boundry is doing? I was looking into it and found this:

 

http://www.regular-expressions.info/wordboundaries.html

 

but it is confusing as hell....

 

EDIT:

 

NVM, just noticed that the second word is apples and not apple and it hit me, lol.

How can I make it case insensitive? For example:

 

$old="apple";

$new="lemon";

 

$str="I have got one green Apple, two yellow apples, oranges and grapes.";

 

echo preg_replace("~\b$old\b~", $new, $str);

 

returns:

 

I have got one green Apple, two yellow apples, oranges and grapes.

 

Is there a way for it to return :

 

I have got one green lemon, two yellow apples, oranges and grapes.

 

Thanks...

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.