skip to Main Content

I need to chnage some words inside strings – I must separate string on 2 or more words – or to add space before and after word. For example I have shopifystore – this must be separated into 2 words”: shopify and store, so result must be: “shopify store”. One more example – I have dogsstore – this must be separated into 2 words”: dogs and store, so result must be: “dogs store”

So, I write some function, but results are not so good. My function:

function englishchange($string) {
$latin = array('dogs','dog','stores','store','shops','shop','shopify');
$latinchanged = array(' dogs ',' dog ',' stores ',' store ',' shops ',' shop ',' shopify ');
return str_replace($latin, $latinchanged, $string);
}
$englishchanged = (englishchange('shopifystore'));

But the resilt from “dogsstore” is: “dog s store” and “shopifystore” going to: “shop ify store”. Can anyone help me, please, to rewrite php code to get the right result?

2

Answers


  1. You can use strtr in its second form to do the replacements. In that mode, it takes an array of replacement pairs and, working from the longest strings downward, having made a replacement, it will not replace that substring again. So you just need to combine your $latin and $latinchanged arrays into an array using array_combine and then call strtr:

    function englishchange($string) {
    $latin = array('dogs','dog','stores','store','shops','shop','shopify');
    $latinchanged = array(' dogs ',' dog ',' stores ',' store ',' shops ',' shop ',' shopify ');
    return strtr($string, array_combine($latin, $latinchanged));
    }
    $englishchanged = (englishchange('dogsstore shopifystore'));
    echo $englishchanged;
    

    Output:

     dogs  store   shopify  store 
    
    Login or Signup to reply.
  2. The problem is that the string matches several search items.
    You can assume that you want only one change per string so you could procede with a loop to avoid the problem :

    function englishchange($string)
    {
        $latin = array('dogs','dog','stores','store','shops','shop','shopify');
        $latinchanged = array(' dogs ',' dog ',' stores ',' store ',' shops ',' shop ',' shopify ');
        foreach ($latin as $key => $item) {
            if (strpos($string, $item) !== false) {
                return str_replace($item, $latinchanged[$key], $string);
            }
        }
    }
    

    This way the altered string will be returned after the first replacement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search