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

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

我在这里找到了 C 中的正则表达式:在 c# 中使用正则表达式替换前导和尾随空格与下划线, 但我无法使其在 php 中工作。

4

3 回答 3

2

您可以使用如下替换:

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

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

于 2012-09-05T06:33:00.337 回答
1

您可以按照 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 */
}
?>
于 2012-09-05T06:29:33.673 回答
0

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

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

?>
于 2012-09-05T06:45:03.507 回答