如何在 php 中有条件地将 3 个或更多空格转换为连字符
How to convert 3 or more spaces to a hyphen conditionally in php
我想将多个空格转换为连字符。
例如,如果字符串中的单词之间有 3 个或更多个连续空格,那么我想将它们转换为连字符。
原始字符串:
$x="Hello world! I am new here.
执行后的字符串:
Hello-world! I am new-here
我试过以下方法,但似乎不能正常工作。
<?php
$str="Hello world! I am new here";
echo preg_replace("/.*\s{3}/","-",$str);
这应该有效
echo preg_replace("/\s\s\s+/", "-", $str);
请试试这个:-
<?php
$str="Hello world! I am new here";
echo preg_replace("/\s{3,}/","-",$str);
?>
注意:它会处理等于或大于 3 的任意数量的空格。谢谢。
使用preg_replace("/ {3,}/", "-", $str)
。 </code> 匹配文字 space 并且 <code>{3,}
表示匹配前面字符的 3 或更多 。
您的正则表达式将替换任何字符序列 (.*
) 后跟恰好 3 ({3}
) 个白色space 字符 (\s
),包括制表符、换行符、等...
我想将多个空格转换为连字符。
例如,如果字符串中的单词之间有 3 个或更多个连续空格,那么我想将它们转换为连字符。
原始字符串:
$x="Hello world! I am new here.
执行后的字符串:
Hello-world! I am new-here
我试过以下方法,但似乎不能正常工作。
<?php
$str="Hello world! I am new here";
echo preg_replace("/.*\s{3}/","-",$str);
这应该有效
echo preg_replace("/\s\s\s+/", "-", $str);
请试试这个:-
<?php
$str="Hello world! I am new here";
echo preg_replace("/\s{3,}/","-",$str);
?>
注意:它会处理等于或大于 3 的任意数量的空格。谢谢。
使用preg_replace("/ {3,}/", "-", $str)
。 </code> 匹配文字 space 并且 <code>{3,}
表示匹配前面字符的 3 或更多 。
您的正则表达式将替换任何字符序列 (.*
) 后跟恰好 3 ({3}
) 个白色space 字符 (\s
),包括制表符、换行符、等...