Home > Software engineering >  preg_replace arabic title like مرحبا-اهلاً-بك-هنا
preg_replace arabic title like مرحبا-اهلاً-بك-هنا

Time:11-30

guys i have tried a lot of function but no one of them help me the way that supposed to be.

i have htaccess to replace URL to freindly URL like (test-test-test-test)

in english everything works fine but in arabic not work (مرحبا-مرحبا-مرحبا-مرحبا) not working probably

// English function work fine! replace long title with dashes 
// ex: hello-world-how-is-everything
    function seoUrl($string) {
        $string = strtolower($string);
        $string = str_replace('&',' ',$string);
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        $string = preg_replace("/[\s-] /", " ", $string);
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }

so i want it to be work in arabic language.. thanks

CodePudding user response:

You need to fix your code in several places, mainly, by matching any Unicode letters/digits and replacing multiple consecutive hyphens or whitespaces with a single one. Also, your replacements need to be adjusted, too:

function seoUrl($string) {
        $string = mb_strtolower($string);
        $string = str_replace('&',' ',$string);
        $string = preg_replace("/[^\w\s-] /u", " ", $string);
        $string = preg_replace("/[\s-] /u", " ", $string);
        $string = preg_replace("/[\s_] /u", "-", $string);
        return $string;
    }

echo seoUrl("Test--  _-__-Test----Test$#%#Test") . PHP_EOL;
echo seoUrl("مرحبا--  _-__مرحباt--مرحباst$#%#مرحبا") . PHP_EOL;
// => test-test-test-test
// => مرحبا-مرحباt-مرحباst-مرحبا

See the PHP demo.

Notes:

  • mb_strtolower($string); - to deal with Unicode strings, mb_strtolower is preferred
  • preg_replace("/[^\w\s-] /u", " ", $string) - with the /u flag, \w and \s match any Unicode word and whitespace chars, so you no longer remove Arabic and other letters/digits; mind you need to replace matches with a space, not an empty string here
  • preg_replace("/[\s-] /u", " ", $string) and preg_replace("/[\s_] /u", "-", $string) - u flag is added, ensures whole consecutive match chunks are replaced, not chars one by one.

CodePudding user response:

<?php
function seoUrl($string) {
    $string = strtolower($string);
    $string = str_replace('&',' ',$string);
    $string = preg_replace("/[chr(0600)-chr(0600FF)a-z0-9_\s-]/is", "", $string);
    $string = preg_replace("/[\s-] /", " ", $string);
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}
var_dump(seoUrl("مرحبا-مرحبا-مرحبا-مرحبا"));

I don't know if this is what you want

  • Related