当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

$string = " Some string ";

//the output should look like this

$output = "___Some string__";

So each leading and trailing whitespace replaced by underscore.

I found the regex for this in C here: Replace only leading and trailing whitespace with underscore using regex in c#

but i couldn't make it work in php.

网友答案:

You could use a replace like:

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

\G matches at the beginning of the string or at the end of the previous match, (?=\s*$) matches if the following is only whitespace at the end of the string. So this expression matches each of the spaces and replaces them with a _.

网友答案:

You can use regex with look ahead as Qtax suggested. An alternate solution using preg_replace_callback is : 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 */
}
?>
网友答案:

This code should work. Let me know if it doesn't.

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

?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: