Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

php - Regular expression - any text to URL friendly one

PHP regular expression script to remove anything that is not a alphabetical letter or number 0 to 9 and replace space to a hyphen - change to lowercase make sure there is only one hyphen - between words no -- or --- etc.

For example:

Example: The quick brown fox jumped Result: the-quick-brown-fox-jumped

Example: The quick brown fox jumped! Result: the-quick-brown-fox-jumped

Example: The quick brown fox - jumped! Result: the-quick-brown-fox-jumped

Example: The quick ~`!@#$%^ &*()_+= ------- brown {}|][ :"'; <>?.,/ fox - jumped! Result: the-quick-brown-fox-jumped

Example: The quick 1234567890 ~`!@#$%^ &*()_+= ------- brown {}|][ :"'; <>?.,/ fox - jumped! Result: the-quick-1234567890-brown-fox-jumped


Anybody have idea for the regular expression?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you seem to want all sequences of non-alphanumeric characters being replaced by a single hyphen, you can use this:

$str = preg_replace('/[^a-zA-Z0-9]+/', '-', $str);

But this can result in leading or trailing hyphens that can be removed with trim:

$str = trim($str, '-');

And to convert the result into lowercase, use strtolower:

$str = strtolower($str);

So all together:

$str = strtolower($str);
$str = trim($str, '-');
$str = preg_replace('/[^a-z0-9]+/', '-', $str);

Or in a compact one-liner:

$str = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $str), '-'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...