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


Replace each leading and trailing whitespace with underscore using regex in php

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

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

我在这里找到了 C 中的正则表达式:在 c# 中使用正则表达式仅将前导和尾随空格替换为下划线但我无法让它在 PHP 中工作。

您可以使用这样的替换:

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

'G字符串开头或上一个匹配项的末尾匹配,如果以下内容只是字符串末尾的空格,则(?='s*$)匹配。因此,此表达式匹配每个空格并用_替换它们。

你可以按照 Qtax 的建议使用正则表达式向前看。使用preg_replace_callback的替代解决方案是:http://codepad.org/M5BpyU6k

<?php
$string = " Some string       ";
$output = preg_replace_callback("/^'s+|'s+$/","uScores",$string); /* Match leading
                                                                     or trailing whitespace */
echo $output;
function uScores($matches)
{
  return str_repeat("_",strlen($matches[0]));  /* replace matches with underscore string of same length */
}
?>

这段代码应该可以工作。如果没有,请告诉我。

<?php 
$testString ="    Some test   ";
echo $testString.'<br/>';
for($i=0; $i < strlen($testString); ++$i){
  if($testString[$i]!=" ")
    break;
  else
    $testString[$i]="_";
}
$j=strlen($testString)-1;
for(; $j >=0; $j--){
  if($testString[$j]!=" ")
    break;
  else
    $testString[$j]="_";
}
echo $testString;
?>