开发者

Using Regular Expressions with PHP to replace text

I have a string 开发者_StackOverflowthat 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


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


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);


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜