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

1

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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);

?>

Comments

0
//every element in $myArray

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

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

}

Comments

0
$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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.