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

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

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.