开发者

What Regex for this?

开发者 https://www.devze.com 2023-03-18 04:18 出处:网络
I try to write a good regex, but even with documentation, I don\'t know how to write the good regex. I\'ve a lot of strings, and I need to clean theses of some characters.

I try to write a good regex, but even with documentation, I don't know how to write the good regex.

I've a lot of strings, and I need to clean theses of some characters.

For exemple :

70%coton/ 30%LINé

should become :

70%COTON-30%LINE

In fact :

  • /\# must be replace by -

  • Spaces must be delete

  • Accentual characters must be replace without accent

开发者_高级运维

How I can do this ?


setlocale(LC_ALL, "en_US.UTF8");

$string = '70%COTON/ 30%LINé';
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$string = preg_replace("#[^\w\%\s]#", "", $string);
$string = str_replace(' ', '-', $string);
$string = preg_replace('#(-){2,}#', ' ', $string);

echo strtoupper($string); // 70%COTON-30%LINE


I would use iconv() for accents:

$text = 'glāžšķūņu rūķīši';
$text = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $text);
echo $text; // outputs "glazskunu rukisi"

To do the rest, I'd add strtoupper() for changing case of letters, str_replace() to get rid of spaces and preg_replace() to convert those few characters to -:

$text = 'glāžšķūņu rūķīši / \\ # test';
$text = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $text);
$text = strtoupper($text);
$text = str_replace(' ', '', $text);
$text = preg_replace('#[/\\#\\\\]+#', '-', $text);
echo $text; // outputs "GLAZSKUNURUKISI-TEST"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号