Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

preg_replace to replace 1st occurence of a string within a string

Status
Not open for further replies.

chrismassey

Programmer
Aug 24, 2007
264
GB
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:

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
 
This function will do what you want. It will replace the first occurrence of a string, and only the first occurrence of the string.

Code:
function str_replace_first($or_string,$string_to_rep,$rep_with){
$mylen=strlen($string_to_rep);
$pos=strpos($or_string,$string_to_rep);
if($pos===FALSE){
return FALSE;
}
else{
$mystr=substr_replace($or_string,$rep_with,$pos,$mylen);
return $mystr;
}
}
So:

str_replace_first("/dir1/dir2/dir3/dir4/dir5","/dir1/dir2","");

Will return "/dir3/dir4/dir5"

Or false if the string to be replaced cannot be found.

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thank you very much, ill give it a try. I'm surprised PHP doesn't have an in-built function to do this already.

Chris
 
Glad I could help.

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top