Welcome Guest, Not a member yet? Register   Sign In
Character replacing inside a string


it'll be the best if i simply illustrate my problem with an example:

i want to write a function which would replace non-English character by english ones:

$str = "Ovo je nešto o čemu sada nećemo raspravljati";


$str = "ovo-je-nesto-o-cemu-sada-necemo-raspravljati";

I'm a bit familiar with the str_replace() function, but how to make it to search for characters (č,ć,đ,š,ž) in one step and replace them by c,c,dj,s,z respectively?

for now, i can do this:

function f_ime_seo($replace,$bythis,$str)
      echo str_replace($replace,$bythis,$str);

and it works well, but the problem is i can put into $replace only one character and i want to be able to check for existence of all those character in one step.

Any suggestions would be appreciated! Thanks

[eluser]Jamie Rumbelow[/eluser]
Using str_replace you can't do it in one step - I'd suggest writing one function that looks for every letter and replaces them one by one. Someone else will probably suggest a much better performing solution but this will do:

function replace_all($string) {
    $string = str_replace('š', 's', $string);
    $string = str_replace('č', 'c', $string);
    $string = str_replace('é', 'e', $string);
    $string = str_replace('ü', 'u', $string);
    $string = str_replace('π', 'pi', $string);

    return $string;

this is what i found on this issue and it works well when adapted to my case (at least for now):

$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);

thanks anyway, maybe i'll come back! Smile

I'm curious as to why you need to remove those characters?

[quote author="rossmurphy" date="1260054600"]I'm curious as to why you need to remove those characters?[/quote]

because i need to use those strings in my URLs and i cannot find the way to decode/convert them to work properly. i can permit
them in URIs but still they cause me problems when i need to use them as variables in my queries.


you can also do smth liek this:
$find = array ('ą', 'č', 'ę');
$replace = array ('a', 'c', 'e');

$str = str_replace($find, $replace, $str);

You could also try mb_str_replace, it handles UTF8 better, much better!
good luck!

Theme © iAndrew 2016 - Forum software by © MyBB