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

时间:2012-09-05 06:28:28

标签: php regex preg-replace whitespace

$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中使用它。

3 个答案:

答案 0 :(得分:2)

您可以使用替换为:

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

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

答案 1 :(得分: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 */
}
?>

答案 2 :(得分: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;

?>
相关问题