Search code examples
phpjavascriptregexpreg-replaceslug

Convert function from Javascript to PHP


I've this javascript function that convert any string into the perfect slug (in my opinion).

function slugGenerator(str) {
  str = str.replace(/^\s+|\s+$/g, '');
  str = str.toLowerCase();

  var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  var to   = "aaaaeeeeiiiioooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }
  str = str.replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '_').replace(/-+/g, '-'); 
  return str;
}

I need to convert it to PHP, I've tried and the result is:

function slugGenerator($str) {
  $str = preg_replace('/^\s+|\s+$/g', '', $str);
  $str = strtolower($str);

  $from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  $to   = "aaaaeeeeiiiioooouuuunc------";

  for ($i = 0, $l = strlen($from); $i<$l ; $i++) {
    $str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  $str = preg_replace('/[^a-z0-9 -]/g', '', $str)
  $str = preg_replace('/\s+/g', '_', $str)

  $str = preg_replace('/-+/g', '-', $str); 
  return $str;
}

I've problems with this for loop:

for ($i = 0, $l = strlen($from); $i<$l ; $i++) {

  // This string
  $str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}

I've not idea on how convert it to PHP, someone could try to convert it?

SOLUTION: Add the strtr_unicode function and use this script:

function slugGenerator($str) {

    $str = preg_replace('/^\s+|\s+$/', '', $str);
    $str = strtolower($str);

    $from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
    $to   = "aaaaeeeeiiiioooouuuunc------";
    $str = strtr_unicode($str, $from, $to);

    $str = preg_replace(
      array("~[^a-z0-9 -]~i", "~\s+~", "~-+~"),
      array("", "_", "-"),
      $str
    );

    return $str;
}

Solution

  • Both strtr and str_split won't work for you cos your code contains unicode chars. There are some useful stuff if you like to use.

    str_split_unicode: https://github.com/qeremy/unicode-tools.php/blob/master/unicode-tools.php#L145
    strtr_unicode: https://github.com/qeremy/unicode-tools.php/blob/master/unicode-tools.php#L223

    Test:

    echo strtr_unicode("Hëëëy, hôw ärê yôü!", $from, $to);
    // outs: Heeey- how are you!
    

    After that, you can use arrays as param for preg_replace;

    $from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
    $to   = "aaaaeeeeiiiioooouuuunc------";
    $str = strtr_unicode("Hëëëy, hôw ärê yôü!", $from, $to);
    echo $str ."\n";
    // according to this line: 
    // str = str.replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '_').replace(/-+/g, '-');
    $str = preg_replace(
        array("~[^a-z0-9 -]~i", "~\s+~", "~-+~"),
        array("-", "_", "-"),
        $str
    );
    echo $str;
    

    Outs;

    Heeey- how are you!
    Heeey-_how_are_you-