0

This function is meant to sanitise a given value but instead it outputs "n-a" as if no value was specified. It has to be the simplest issue but right this moment it has me beat.

function slug($text){ 

  // replace non letter or digits by -
  $text = preg_replace('~[^pLd]+~u', '-', $text);

  // trim
  $text = trim($text, '-');

  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

  // lowercase
  $text = strtolower($text);

  // remove unwanted characters
  $text = preg_replace('~[^-w]+~', '', $text);

  if (empty($text))
  {
    return 'n-a';
  }

  return $text;
}

I'd appreciate some input.

2
  • 2
    Where does it become empty? Have you tried dumping the variable as you go along? (after replace, after trim, after strtolower, after second replace) Commented Apr 9, 2014 at 9:26
  • $text = preg_replace('~[^-w]+~', '', $text); this removes everything other than - and w. I think your string does not have - or w. so you are getting empty string. try to rewrite regex here Commented Apr 9, 2014 at 9:37

2 Answers 2

2

You need to change your first regex which seems to be incorrect, should be,

// replace non letter or digits by -
$text = preg_replace('~[^\w\d]+~u', '-', $text);

Working Demo.

Sign up to request clarification or add additional context in comments.

2 Comments

I think he meant \pL\d (aka. unicode letter/digit).
@h2ooooooo - adding backslashes solved my problem i.e. first regex to \pL\d and the second to \w
1
  1. Try using mb_string library instead of iconv. Its a better library.
  2. At each instance try var_dump or echo to make sure the return of the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.