Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim consecutive duplicate characters

Tags:

regex

php

So I'm creating urls for my pages by doing the following:

$uri = strtolower($info->name);
$uri = str_replace('&','and',$uri);

$uri = $info->id."-".preg_replace('/[^a-zA-Z0-9]/','-',$uri);

Basically I make everything lowercase, change & to and and change all special characters to a -. My only problem now if for instance $info->name is this is - a string it will show up as this-is---a-string.

I would like this to become this-is-a-string without doing something like str_replace('---','-',$input);

I figure I need a regular expression for this, but I'm horrible at those so I was wondering if someone can help me out.

like image 815
Kokos Avatar asked Feb 23 '23 08:02

Kokos


1 Answers

Change

$uri = $info->id."-".preg_replace('/[^a-zA-Z0-9]/','-',$uri);

to

$uri = $info->id."-".preg_replace('/[^a-zA-Z0-9]+/','-',$uri);
like image 102
Dogbert Avatar answered Feb 25 '23 20:02

Dogbert