Jump to content

[SOLVED] Search and Replace in String


the_oliver

Recommended Posts

Hello,

 

Im using the following to search for charictors in a string that are causing problems, and placing a \ infrount of them.  Im trying to do it using:

 

<?php
$str = "string's";
$invalied_chars = array(" ", "'");
$result = str_replace($invalied_chars, "\\", $str);
echo $result;
?>

 

The bit im confused by was how to keep the old charictor, just proceeding it with a \ rather then replacing it?

 

Thanks

 

 

Link to comment
https://forums.phpfreaks.com/topic/54303-solved-search-and-replace-in-string/
Share on other sites

I believe that would cause an error since $invalied_chars is an array, shoud be like this:

<?php
$str = "string's";
$invalied_chars = array(" ", "'");
$result = $str;
foreach ($invalied_chars as $i) {
$result = str_replace($i, "\\", $result);}
echo $result;
?>

That should work better I think, but I dont understand your question...

Ted

Thanks.  Worked well other then with the < charictor.  ( the output i was expecting was \> )

 

Im trying:

$str            = "<";
$invalied_chars = array("<");
$writein        = array("\\<");
$result         = str_replace($invalied_chars, $writein, $str);

echo $result;

 

I also tried:

$writein        = array("\\<");

and got the output \\

 

And

$str            = "<";

and got the output \\\

 

Can any one suggest where im wrong?

 

Thanks!

 

 

EDIT: i cant use < of char() as it will end up being output to create a unix file name, not for web output.

How are you viewing the results? Via a web browser or directly via the CLI? If you're viewing it via a browser, the "<" character is probably there but is being eaten by the browser because it thinks the character is the start of a tag. Do a "show source" and you will probably see the character in the source.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.