Search code examples
phpcontains

php variable contains string and replace


Very new to PHP, but I have this code

$url =  'http://example.com/en-us/about-us';

    if ($url contains 'en-us') {
        replace 'en';
    }

does anyone know how I would get this to work.

Basically if the URL contains en-us replace the url with en

Thanks


Solution

  • $url =  'http://example.com/en-us/about-us';
    
    if (strpos($url,'en-us') !== false) { //first we check if the url contains the string 'en-us'
        $url = str_replace('en-us', 'en', $url); //if yes, we simply replace it with en
    }
    

    I hope this could be some help for you