PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How can i replace words in a string using an array in php?

 November 20, 2022     arrays, php, preg-replace     No comments   

Issue

I am trying to search a string and replace all instances of a certain string with another other string every time the first string appears.

My goal is to avoid using many preg-replace statements and to make an array which is easily editable and maintainable, containing keys that are identical to the words i'm looking to replace and values containing the replacements.

So far I've got something like this:

$colors = array('red' => 'i am the color red', 'blue' => 'hi I am       blue',);

$string = "red, blue, red, and lots of blue";
foreach($colors as $key => $value) {
    preg_replace($key, $value, $string);
    echo $string;
}

This is not yet working.


Solution

You are doing straight string replacement (no regular expressions) so use:

$string = str_replace(array_keys($colors), $colors, $string);

No loop needed, str_replace() takes arrays.

FYI: In your code, aside from the parse error, you aren't assigning the return of the preg_replace() back to a string to be used and regex using a specific a pattern with delimiters and special syntax. You need word boundaries \b as well to keep from replacing the red in redefine and undelivered etc.:

$string = preg_replace("/\b$key\b/", $value, $string);


Answered By - AbraCadaver
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing