Nick_Core
Nick_Core

Reputation: 136

convert ", " INTO "-" with regular expressions using PHP

I want to obtain this

dog-cat-mouse

From each one of those

What i came up with is 2 preg_replace

$str = preg_replace('/[,\s]/', '-', $str);
$str = preg_replace('/--/', '-', $str);

works on my local server BUT does not work on production, it gives me

dog, cat, mouse -> dog--cat--mouse

which is not what I want

Upvotes: 0

Views: 40

Answers (2)

walid toumi
walid toumi

Reputation: 2272

preg_replace('/,\h*|\h+/', '-', $str)

Use \h instead of \s

Upvotes: 0

zerkms
zerkms

Reputation: 254886

You need + quantifier for your [,\s] character set.

What it changes is that it now means not "any comma or a whitespace character" but "any consecutive commas and whitespace characters"

preg_replace('/[,\s]+/', '-', $str)

Upvotes: 2

Related Questions