3
$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.

3 Answers 3

2

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 _.

Sign up to request clarification or add additional context in comments.

2 Comments

@RazvanO. this isn't completely trivial to do with regex, so the regex is a bit tricky. :-)
Nice one! Even if those other solutions did work, this is the one I would use, in .NET as well as PHP.
1

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 */
}
?>

Comments

0

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;

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.