string replacement
Moderator: General Moderators
string replacement
I have this problem with string replacement... I have a string and I want to leave some symbols in it and all the other symbols replace with "-"... I know that there are functions, that replace all the given symbols, but I need the function to replace all the "not given" symblos. Is there a function like this?
Re: string replacement
Sounds like you need preg_replace(). Without any code it'll be hard to provide any personalised help, though.
Re: string replacement
I think it isnt the right one... I will try to give an example... I have a string and want it to contain only symbols "a", "b" and "-"... So what can I do to replace all other symbols with "-"?foobar wrote:Sounds like you need preg_replace(). Without any code it'll be hard to provide any personalised help, though.
str_replace should do the trick
example:
example:
Code: Select all
$replaced_string = str_replace(array("&", "%", "#"), "-", $string);Code: Select all
$string = preg_replace('/[^ab-]{1}/', '-', $string);Based on his description of the problem, str_replace() is going to need a search array that's much larger then what you provided. It's not practical by comparison to preg_replace().mickd wrote:str_replace should do the trick
example:
Code: Select all
$replaced_string = str_replace(array("&", "%", "#"), "-", $string);
Cheers
ah yeah, only realised afterwards that he wanted to keep so few. preg_replace would be better in that caseBDKR wrote:
Based on his description of the problem, str_replace() is going to need a search array that's much larger then what you provided. It's not practical by comparison to preg_replace().
Cheers
Example:Pain wrote:thanks, I just could not find how I could replace the "incorrest" symbols, but now I know and my wisdom has grown
Code: Select all
<?php
$input = 'I love apples! 2me1three. <some smurf />';
$bad_boys = '/[\w]+/'; //bad "symbols" are non perl-words
$good_guy = '-';
$string = preg_replace($bad_boys, $good_guy, $input);
echo $string;
$bad_boys = '/[^a-zA-Z0-9]+/'; //non alphanumeric characthers (^ is the negation of everything within [])
$good_guy = '-';
$string = preg_replace($bad_boys, $good_guy, $input);
echo $string;
$bad_boys = '/[\^°@~+#?\]\[\(\)\$\!]+/'; //a bunch of non-alphanumeric characters
$good_guy = '-';
$string = preg_replace($bad_boys, $good_guy, $input);
echo $string;
?>