chrismassey
Programmer
Hello,
I am using a script to display the entire contents of a folder. At one stage in my code, I must replace the first occurence of a string within another string.
For example:
$string = '/dir1/dir2/dir3/dir4/dir5';
$replace = '/dir1/dir2';
$replace_with = '';
I would assume that if I did this:
$string = preg_replace("/$replace/", $replace_with, $string, 1);
Then the result would be:
echo "$string";
// ( /dir3/dir4/dir5 )
However this is not the result I am getting, instead $string is blank. What am I doing wrong or how can I replace just the first occurence?
I must only replace the first occurence because $replace may often be just '/', therefore all /'s would be replaced, which isn't acceptable.
I have included my code below:
Thanks alot,
Chris
I am using a script to display the entire contents of a folder. At one stage in my code, I must replace the first occurence of a string within another string.
For example:
$string = '/dir1/dir2/dir3/dir4/dir5';
$replace = '/dir1/dir2';
$replace_with = '';
I would assume that if I did this:
$string = preg_replace("/$replace/", $replace_with, $string, 1);
Then the result would be:
echo "$string";
// ( /dir3/dir4/dir5 )
However this is not the result I am getting, instead $string is blank. What am I doing wrong or how can I replace just the first occurence?
I must only replace the first occurence because $replace may often be just '/', therefore all /'s would be replaced, which isn't acceptable.
I have included my code below:
Code:
$original_dir_path = '/dir1/dir2';
$new_dir_pathb = '/dir1/dir2/dir3/dir4/dir5';
[COLOR=red]$new_dir_pathb = preg_replace("/$original_dir_path/", '', $new_dir_pathb, 1);[/color]
echo "<br>result: $new_dir_pathb"; // The result is empty
Thanks alot,
Chris