gpt4 book ai didi

php - 在 php 中使用正则表达式将每个前导和尾随空格替换为下划线

转载 作者:搜寻专家 更新时间:2023-10-31 20:46:48 25 4
gpt4 key购买 nike

$string = "   Some string  ";
//the output should look like this
$output = "___Some string__";

因此每个前导和尾随空格都被下划线替换。

我在 C 中找到了正则表达式:Replace only leading and trailing whitespace with underscore using regex in c#但我无法让它在 php 中工作。

最佳答案

您可以使用这样的替换:

$output = preg_replace('/\G\s|\s(?=\s*$)/', '_', $string);

\G 匹配字符串的开头或前一个匹配的结尾,(?=\s*$) 如果后面只有空格则匹配在字符串的末尾。所以这个表达式匹配每个空格并将它们替换为 _

关于php - 在 php 中使用正则表达式将每个前导和尾随空格替换为下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12275643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com