-1

This is what I've tried, but it didn't remove the apostrophe, is there a better way to do it?

$title = strtr($title, array('.' => '', ',' => '', '!' => '', '\''  => ''));
$title = preg_replace('/\s+/', '-', $title);

So for example I would want to turn:

Example:

Let's Start! => lets-start

But I'm trying to find a solution that works for all cases.

James Mitchell
  • 2,387
  • 4
  • 29
  • 59

3 Answers3

4

You could use this expression:

strtolower(preg_replace("#\s+#u", "-", preg_replace("#[^\w\s]|_#u", "", $title)))

Note: if your original string contains HTML encoding, like ’, then you must first decode it with:

$title = html_entity_decode($title);
trincot
  • 317,000
  • 35
  • 244
  • 286
0
$string = mb_strtolower( strtr("Let's start!", array('.' => '', ',' => '', '!' => '', '\''  => '') ) );
echo  $string = preg_replace("/[\s]/", "-", $string);

This should replace the characters, then change all spaces to dashes for you.

Ice76
  • 1,143
  • 8
  • 16
  • Having an issue with the apostrophe, I think it could be a wordpress issue. It's pulling the_title variable. – James Mitchell Jul 21 '17 at 21:16
  • @JamesMitchell The variation would be to use `"'" => ''` instead. (Double quotes surrounding the single quote) – Ice76 Jul 21 '17 at 21:29
0

You can get the same result without regx

Example:

$title = "Let's Start!";
$title = strtr(strtolower($title), array('.' => '', ',' => '', '!' => '', '\''  => ''));
$title = str_replace(' ','-',trim($title));

echo $title; //Output: lets-start
Rashid
  • 272
  • 2
  • 6