2

I have a string that is something like "apple|banana|peach|cherry".

How can I use regular expressions to search this list and replace another string with a certain value if there is a match?

For example:

$input = 'There is an apple tree.';

Change that to: "There is an <fruit>apple</fruit> tree."

Thanks, Amanda

4 Answers 4

8

Try this:

<?php
$patterns ="/(apple|banana|peach|cherry)/";

$replacements = "<fruit>$1</fruit>";

$output = preg_replace($patterns, $replacements, "There is an apple tree.");
echo $output;
?>

For more details please look at the php manual on preg_replace

Update: @Amanda: As per your comment you may modify this code to:

$patterns ="/(^|\W)(apple|banana|peach|cherry)(\W|$)/";
$replacements = "$1<fruit>$2</fruit>$3";

to avoid matching impeach and scrapple

Sign up to request clarification or add additional context in comments.

Comments

0

preg_replace function

Although, if you want to match directly, it's faster to use str_replace or str_ireplace like that:

$text = "some apple text";
$fruits = explode("|", "apple|orange|peach");
$replace = array('replace apple', 'replace orange', 'replace peach');

$new = str_replace($fruits, $replace, $text);

2 Comments

Thanks! That's really helpful! Is there a way to keep words like IMPEACH or SCRAPPLE from getting tagged as fruits?
@Amanda: As per your comment you may modify my code above to: $patterns ="/(^|\W)(apple|banana|peach|cherry)(\W|$)/"; $replacements = "$1<fruit>$2</fruit>$3"; to avoid matching impeach and scrapple
0
$input = 'There is an apple tree.';
$output = preg_replace('/(apple|banana|peach|cherry)/', "<fruit>$1</fruit>", $input);

1 Comment

Got it:$input = 'There is an apple tree.'; $output = preg_replace('/(apple|banana|peach|cherry)/', "<fruit>$1</fruit>", $input);
0

Overall there is probably a better way to do this, but that would involve you giving a lot more details about your setup and overall goal. But you can do this:

$input = preg_replace('~(apple|banana|peach|cherry)~','&lt;fruit>$1&lt;/fruit>',$input);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.