sohel14_cse_ju
sohel14_cse_ju

Reputation: 2521

Replace parent directory name in filepath strings

Array {
    [0] => http://example1.com/video/ghgh23;
    [1] => http://example2.com/file/mwerq2;
}

I want to replace the content between /sometext/ from the above array. Like I want to replace video, file with abc.

Upvotes: 0

Views: 624

Answers (6)

Hans Henrik
Hans Henrik

Reputation: 63

$array = array('http://abc.com/video/ghgh23', 'http://smtech.com/file/mwerq2');
foreach ($array as &$string)
{
    $string = str_replace('video', 'abc', $string);
    $string = str_replace('file', 'abc', $string);
}

Upvotes: 0

ircmaxell
ircmaxell

Reputation: 165193

You don't need to loop over every element of the array, str_replace can take an array to replace with:

$myArray = str_replace(array('/video/', '/file/'), '/abc/', $myArray);

However, based on your question, you might want to replace the first path segment, and not a specific index. So to do that:

$myArray = preg_replace('((?<!/)/([^/]+)/)', '/abc/', $myArray);

That will replace the first path element of every URL in $myArray with /abc/...

Upvotes: 2

davidhaskins
davidhaskins

Reputation: 280

//every element in $myArray

for($i=0; $i < count($myArray); $i++){

    $myArray[$i] = str_replace('/video/','/abc/',$myArray[$i]);

}

Upvotes: 0

Richard Dev
Richard Dev

Reputation: 1170

This is another option. Supply a array, foreach will pick it up and then the first parameter of str_replace can be a array if needed. Hope you find this helpful.

<?php

$array = array('http://abc.com/video/ghgh23','http://smtech.com/file/mwerq2');
$newarray = array();

foreach($array as $url) {
 $newarray[] = str_replace(array('video','file'),'abc',$url);
}

print_r($newarray);

?>

Upvotes: 0

applechief
applechief

Reputation: 6895

Either str_replace as other comments suggested or using a regular expression especially if you might have a longer url with more segments like http://example.com/xxx/somestuff/morestuff In that case str_replace will not be enough you will need preg_replace

Upvotes: 0

mewm
mewm

Reputation: 1277

One way is to use str_replace() You can check it out here: http://php.net/str_replace

Upvotes: 0

Related Questions