[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

PHP Search and Replace in String Array

So i have an array, you can see in the code below, what i want to do is parse through it and replace various characters different characters, I have my function you can see to do this, it works but only executes the last str_replace, it doesnt do all of them  Below the function i call the text as

<?=$text["Title"]?>

so when it comes out it needs to be clean and replaced by all of the str_replaced not just the last one.
<?php

$text = array(

	"Title" => "Hello & World!",
	"Heading" => "I’m",
	"Bottom" => "I hate & ””People"
)
?>


<?php


foreach($text as $key=>$value) {
    $text[$key] = str_replace("&", "cool", $value);
    $text[$key] = str_replace("’", "'", $value);
    $text[$key] = str_replace("“", "&quot;", $value);
    $text[$key] = str_replace("”", "&quot;", $value);
}



?>

Open in new window

0
Brant Snow
Asked:
Brant Snow
3 Solutions
 
steveo225Commented:
Try:
<?php

$text = array(

        "Title" => "Hello & World!",
        "Heading" => "I’m",
        "Bottom" => "I hate & ””People"
)
?>


<?php


foreach($text as $key=>$value) {
    $value = str_replace("&", "cool", $value);
    $value = str_replace("’", "'", $value);
    $value = str_replace("“", "&quot;", $value);
    $text[$key] = str_replace("”", "&quot;", $value);
}



?>

Open in new window

0
 
rkeith2412Commented:
give this a try
$text = array( 
 
        "Title" => "Hello & World!", 
        "Heading" => "I’m", 
        "Bottom" => "I hate & ””People" 
); 

$find = array("&", "’", "“", "”");
$replace = array("cool", "'", "&quot;", "&quot;");

 
foreach($text as $key=>$value) { 
    $text[$key] = str_replace($find, $replace, $value); 
} 

Open in new window

0
 
john-formbyCommented:
Hi,

Please have a look at the following.

Hope this helps,

John
<?php 
$text = array( 
        "Title" => "Hello & World!", 
        "Heading" => "I’m", 
        "Bottom" => "I hate & ””People" 
) 
?> 

<?php 
foreach($text as $key=>$value) { 
    $text[$key] = str_replace(array("&","’","“","”"), array("cool","'","&quot;","&quot;"), $value); 
} 
print_r($text);
?>

Open in new window

0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now