Reputation: 326
So I'm kind of stuck on this - I'm looking to replace text in an array (easily done via str_replace), but I would also like to append text onto the end of that specific array. For example, my original array is:
Array (
[1] => DTSTART;VALUE=DATE:20130712
[2] => DTEND;VALUE=DATE:20130713
[3] => SUMMARY:Vern
[4] => UID:1fb5aa60-ff89-429e-80fd-ad157dc777b8
[5] => LAST-MODIFIED:20130711T010042Z
[6] => SEQUENCE:1374767972
)
I would like to search that array for ";VALUE=DATE" and replace it with nothing (""), but would also like to insert a text string 7 characters after each replace ("T000000"). So my resulting array would be:
Array (
[1] => DTSTART:20130712T000000
[2] => DTEND:20130713T000000
[3] => SUMMARY:Vern
[4] => UID:1fb5aa60-ff89-429e-80fd-ad157dc777b8
[5] => LAST-MODIFIED:20130711T010042Z
[6] => SEQUENCE:1374767972
)
Is something like this possible using combinations of str_replace, substr_replace, etc? I'm fairly new to PHP and would love if someone could point me in the right direction! Thanks much
Upvotes: 1
Views: 1533
Reputation: 2740
for($i=0;$i<count($array);$i++){
if(strpos($array[$i], ";VALUE=DATE")){//look for the text into the string
//Text found, let's replace and append
$array[$i]=str_replace(";VALUE=DATE","",$array[$i]);
$array[$i].="T000000";
}
else{
//text not found in that position, will not replace
//Do something
}
}
If you want just to replace, just do it
$array=str_replace($array,";VALUE=DATE","");
And will replace all the text in all the array's positions...
Upvotes: 0
Reputation: 437376
You can use preg_replace
as an one-stop shop for this type of manipulation:
$array = preg_replace('/(.*);VALUE=DATE(.*)/', '$1$2T000000', $array);
The regular expression matches any string that contains ;VALUE=DATE
and captures whatever precedes and follows it into capturing groups (referred to as $1 and $2 in the replacement pattern). It then replaces that string with $1 concatenated to $2 (effectively removing the search target) and appends "T000000"
to the result.
Upvotes: 4
Reputation: 72981
The naive approach would be to loop over each element and check for ;VALUE=DATE
. If it exists, remove it and append T000000
.
foreach ($array as $key => $value) {
if (strpos($value, ';VALUE=DATE') !== false) {
$array[$key] = str_replace(";VALUE=DATE", "", $value) . "T000000";
}
}
Upvotes: 1
Reputation: 8349
You are correct str_replace()
is the function that you are looking for. In addition you can use the concatenation operator .
to append your string to the end of the new string. Is this what you are looking for?
$array[1] = str_replace(";VALUE=DATE", "", $array[1])."T000000";
$array[2] = str_replace(";VALUE=DATE", "", $array[2])."T000000";
Upvotes: 0