任何对URL友好的文本

任何对URL友好的文本

本文介绍了正则表达式-任何对URL友好的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP正则表达式脚本要删除不是字母字母或数字0到9的所有内容,并用连字符代替空格-更改为小写以确保在单词no-或---之间只有一个连字符.

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.

例如:

示例:敏捷的棕色狐狸跳了起来结果:快速棕色狐狸跳了

Example: The quick brown fox jumpedResult: 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

示例:快速1234567890〜`!@#$%^& *()_ + = -------棕色{} |] [:';<>?.,/fox-跳了!结果:the-quick-1234567890-brown-fox-jumped

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

有人对正则表达式有想法吗?

Anybody have idea for the regular expression?

谢谢!

推荐答案

由于您似乎希望将所有非字母数字字符序列替换为单个连字符,因此可以使用以下方法:

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);

但这会导致前导或尾随的连字符,可以使用 trim

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

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

要将结果转换为小写,请使用 strtolower :

And to convert the result into lowercase, use strtolower:

$str = strtolower($str);

所以在一起:

$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), '-'));

这篇关于正则表达式-任何对URL友好的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:52