Marvin Saldinger
Marvin Saldinger

Reputation: 1400

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.

Upvotes: 3

Views: 1989

Answers (3)

raghav.mohan
raghav.mohan

Reputation: 9

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;

?>

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43265

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

Upvotes: 1

Qtax
Qtax

Reputation: 33928

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

Upvotes: 2

Related Questions