开发者

Replacing a string inside a string in PHP

I have strings in my application that us开发者_JAVA技巧ers can send via a form, and they can optionally replace words in that string with replacements that they also specify. For example if one of my users entered this string:

I am a user string and I need to be parsed.

And chose to replace and with foo the resulting string should be:

I am a user string foo I need to be parsed.

I need to somehow find the starting position of what they want to replace, replace it with the word they want and then tie it all together.

Could anyone write this up or at least provide an algorithm? My PHP skills aren't really up to the task :(

Thanks. :)


$result = preg_replace('/\band\b/i', 'foo', $subject);

will find all occurences of and where it's a word on its own and replace it with foo. \b ensures that there is a word boundary before and after and.


use preg_replace. You don't need to think so hard about this though you will have to learn a little bit about regexes. :)


Read up on str_replace, or for more complex replacements on Regular Expressions and preg_replace.

Examples for both:

<?php
$str = 'I am a user string and I need to be parsed.';
echo str_replace( 'and', 'foo', $str ) . "\n";
echo preg_replace( '/and/', 'foo', $str ) . "\n";
?>

In response to the comments of this answer, note that both examples above will replace every occurrence of the search string (and), even when it happens to be within another word.

To take care of that you either have to add the word separators to the str_replace call (see the comment of an example), but this will get quite complicated when you want to take care of all common word separators (space, commas, dots, exclamation marks, question marks etc.).

An easier to way to fix this problem is to use the power of regular expressions and make sure, the actual search string is not found within another word. See Tim Pietzcker's example below for a possible solution.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜