我需要将一些字符串组合引入一个模式,即应删除多个空格,双连字符应替换为单个超文本,单个空格应替换为单个连字符.
我已经尝试过这个表达式.
$output = preg_replace( "/[^[:space:]a-z0-9]/e", "", $output );
$output = trim( $output );
$output = preg_replace( '/\s+/', '-', $output );
Run Code Online (Sandbox Code Playgroud)
但这在几个组合中失败了.
我需要帮助才能使所有这些组合完美地运作:
1. steel-black
2. steel- black
3. steel black
Run Code Online (Sandbox Code Playgroud)
我也应该删除其中任何一个\r\n\t.
你可以使用这样的东西(感谢更好的建议 @Robin):
$s = 'here is a test-- with -- spaces-and hyphens';
$s = preg_replace('/[\s-]+/', '-', $s);
echo $s;
Run Code Online (Sandbox Code Playgroud)
用一个连字符替换任意数量的空白字符或连字符.您可能还想使用trim($s, '-')删除任何前导或尾随连字符.也可以在正则表达式中直接执行此操作,但我认为更明确的是不要这样做.
输出:
here-is-a-test-with-spaces-and-hyphens
Run Code Online (Sandbox Code Playgroud)
如果您要删除其他字符,只需将它们添加到括号表达式中,例如/[()\s-]+/也可以删除括号.但是,您可能更愿意只替换所有非单词字符:
$s = 'here is a test- with -- spaces ( ), hyphens (-), newlines
and tabs ( )';
$s = trim(preg_replace('/[\W]+/', '-', $s), '-');
echo $s;
Run Code Online (Sandbox Code Playgroud)
这将替换除[a-zA-Z0-9_]连字符以外的任何数量的字符,并删除任何前导和尾随连字符.
输出:
here-is-a-test-with-spaces-hyphens-newlines-and-tabs
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1714 次 |
| 最近记录: |