Search and Replace Multiple Values with Multiple/Different Values in PHP5

Search and replace multiple values with multiple/different values in PHP5?

You are looking for str_replace().

$string = 'blah blarh bleh bleh blarh';
$result = str_replace(
array('blah', 'blarh'),
array('bleh', 'blerh'),
$string
);

// Additional tip:

And if you are stuck with an associative array like in your example, you can split it up like that:

$searchReplaceArray = array(
'blah' => 'bleh',
'blarh' => 'blerh'
);
$result = str_replace(
array_keys($searchReplaceArray),
array_values($searchReplaceArray),
$string
);

How to replace multiple items from a text string in PHP?

You can pass arrays as parameters to str_replace(). Check the manual.

// Provides: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = ["fruits", "vegetables", "fiber"];
$yummy = ["pizza", "beer", "ice cream"];

$newPhrase = str_replace($healthy, $yummy, $phrase);

Replace multiple occurrences of a string with different values

I don't think you can do this using any of the search and replace functions, so you'll have to code up the replace yourself.

It looks to me like this problem works well with explode(). So, using the example token generator you provided, the solution looks like this:

$shrapnel = explode('%%token%%', $str);
$newStr = '';
for ($i = 0; $i < count($shrapnel); ++$i) {
// The last piece of the string has no token after it, so we special-case it
if ($i == count($shrapnel) - 1)
$newStr .= $shrapnel[$i];
else
$newStr .= $shrapnel[$i] . rand(100,10000);
}

PHP how to replace multiple strings

I think you're looking for the explode and implode functions. You can do something like this which breaks your string into an array, you can modify the array elements, then combine them back into a string.

$str = "have:a:good:day:";

$tokens = explode(":", $str);
//$tokens => ["have", "a", "good", "day", ""]

$tokens[2] = "newString1";
//$tokens => ["have", "a", "newString1", "day", ""]

$str2 = implode(":", $tokens);
//$str2 => "have:a:good:day:"

Alternatively if you just want to replace certain words in the string, you can use the str_replace function to replace one word with another. Eg.

$str = "have:a:good:day:";
$str2 = str_replace("good", "newString1", $str);
//$str2 => "have:a:newString1:day:";

Foreach loop using multiple str_replace

str_replace can replace array of values to array of other values:

foreach ($icons as $ic) {
echo str_replace(
array('{{EMP_NO}}', '{{FIRST_NAME}}'),
array($_SESSION['EmpNo'], $_SESSION['FirstName']),
$ic['url']) . ' '
);
}

And as already mentioned in @David's answer, though your code has a correct syntax, but its' logic is flawed.

str_replace characters with 2 other characters

Just read the documentation:

$bodyweight = str_replace(array("'", ','), array("`", '.'), $form->data['bodyweight']);

Str_replace for multiple items

str_replace() can take an array, so you could do:

$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);

Alternatively you could use preg_replace():

$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);

Replace multiple placeholders with PHP?

Simple, see strtr­Docs:

$vars = array(
"[{USERNAME}]" => $username,
"[{EMAIL}]" => $email,
);

$message = strtr($message, $vars);

Add as many (or as less) replacement-pairs as you like. But I suggest, you process the template before you call the phpmailer function, so things are kept apart: templating and mail sending:

class MessageTemplateFile
{
/**
* @var string
*/
private $file;
/**
* @var string[] varname => string value
*/
private $vars;

public function __construct($file, array $vars = array())
{
$this->file = (string)$file;
$this->setVars($vars);
}

public function setVars(array $vars)
{
$this->vars = $vars;
}

public function getTemplateText()
{
return file_get_contents($this->file);
}

public function __toString()
{
return strtr($this->getTemplateText(), $this->getReplacementPairs());
}

private function getReplacementPairs()
{
$pairs = array();
foreach ($this->vars as $name => $value)
{
$key = sprintf('[{%s}]', strtoupper($name));
$pairs[$key] = (string)$value;
}
return $pairs;
}
}

Usage can be greatly simplified then, and you can pass the whole template to any function that needs string input.

$vars = compact('username', 'message');
$message = new MessageTemplateFile('email.tpl', $vars);


Related Topics



Leave a reply



Submit