1

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

4

4 回答 4

4

您可以将preg_replace其用作此类操作的一站式商店:

$array = preg_replace('/(.*);VALUE=DATE(.*)/', '$1$2T000000', $array);

正则表达式匹配任何字符串,该字符串包含;VALUE=DATE并捕获它之前和之后的任何内容进入捕获组(在替换模式中称为 $1 和 $2)。然后它用连接到 $2 的 $1 替换该字符串(有效地删除搜索目标)并附"T000000"加到结果中。

于 2013-07-25T21:49:46.260 回答
1

天真的方法是遍历每个元素并检查;VALUE=DATE. 如果存在,请将其删除并附加T000000.

foreach ($array as $key => $value) {
  if (strpos($value, ';VALUE=DATE') !== false) {
    $array[$key] = str_replace(";VALUE=DATE", "", $value) . "T000000";
  }
}
于 2013-07-25T21:48:39.070 回答
0
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
   }
}

如果您只想更换,请执行此操作

$array=str_replace($array,";VALUE=DATE","");

并将替换所有数组位置中的所有文本...

于 2013-07-25T21:57:36.660 回答
0

你是正确str_replace()的,你正在寻找的功能。此外,您可以使用连接运算符.将您的字符串附加到新字符串的末尾。这是你想要的?

$array[1] = str_replace(";VALUE=DATE", "", $array[1])."T000000";
$array[2] = str_replace(";VALUE=DATE", "", $array[2])."T000000";
于 2013-07-25T21:47:48.560 回答