preg replace complete word using partial patterns in PHP

I am using preg_replace($oldWords, $newWords, $string); to replace an array of words.

I wish to replace all words starting with foo into hello, and all words starting with bar into world

i.e foo123 should change to hello , foobar should change to hello, barx5 should change to world, etc.

If my arrays are defined as:

$oldWords = array('/foo/', '/bar/');  
$newWords = array('hello', 'world');

then foo123 changes to hello123 and not hello. similarly barx5 changes to worldx5 and not world

How do I replace the complete matched word?



This is actually pretty simple if you understand regex, as well as how preg_replace works.

Firstly, your replacement arrays are incorrectly formed. What is:

$oldWords = array('\foo\', '\bar\');

Should instead be:

$oldWords = array('/foo/', '/bar/');

As the backslash in php escapes the character after it, meaning your strings were getting turned into non-strings, and it was messing up the rest of your code.

As to your actual question, however, you can achieve the desired effect with this:

$oldWords = array('/foo\w*/', '/bar\w*/');

\w matches any word character, while * is a quantifier either meaning 0 or any number of matches.

Adding in those two items will cause the regex to match any string with foo and x number of word-characters directly after it, which is what preg_replace then replaces; the match.

one way to do it is to loop through the array checking each word, since we are only checking the first three letters I would use a substr() instead of a regex because regex functions are slower.

    foreach( $oldWords as $word ) {

        $newWord = substr( $word, 0, 2 );

        if( $newWord === 'foo'  ) {
            $word = 'hello';
        else if( $newWord === 'bar' ) {
            $word = 'world';


Need Your Help

php mysql get 2 table value

php mysql

Now I would like to query data to do the newest get code.

Post parameters in two forms when onchange happens in one of them

html jsp jstl

I have dropdown lists in two forms in a single .jsp. I would like the change of any of the lists to trigger a post back to the .jsp itself with the currently selected parameters in both forms. But I