Web Hosting Talk







View Full Version : PHP - Replace a string just once?


P-nut
02-05-2006, 01:47 PM
Say I have a variable such as
$_SERVER['REQUEST_URI'];

which outputs

/folder/

Is there a way to replace just the first / in /folder/?

Christopher Lee
02-05-2006, 02:40 PM
Probably a more elegant solution than this...my example is just a quickie:


unset($var);
unset($first);

$var = '/folder/';

$first = $var{0};

if('/' == $first){
$var = substr($var, 1);
}

echo 'Var is: ' . $var . '<br>';


The manual: substr (http://us3.php.net/manual/en/function.substr.php)

P-nut
02-05-2006, 03:23 PM
Thanks, Christopher! At least I know what I'm looking for now :)

Burhan
02-06-2006, 01:55 AM
$var = '/folder/';
$var{0} = 'z';
echo $var; #this is now zfolder/

ScriptBlue
02-06-2006, 07:20 PM
you could do
$var = preg_replace("#^(/)#", "newvaluefor/", $folder);
^ means that / is at the begging of the string

ZiDev
02-06-2006, 07:49 PM
Not a valid regular expression though... Try
$var = preg_replace('#^/(.*?))#', '$1', $folder);

Yours would always return // for $var.

-- HW

Elliot A
02-07-2006, 12:32 AM
A regular expression is overkill.

If your only wanting to change one character then just use fyrestrtr's example or extract what you want using substr.