PHP:从数组中的值中删除正则表达式字符串

时间:2014-06-06 07:32:03

标签: php arrays regex

我有一个数组$text

Array
(
    [0] => "(This is so cool!)"
    [1] => "look at @[48382669205:275:JAY Z] and @[28940545600:27:Beyonc\303\251]'s page"
    [2] => "@[30042869909:32:Van Jones] on Bowe Bergdahl drama"    
)

我想匹配删除@ [0-9]文本,所以我的输出如下:

Array
(
    [0] => "(This is so cool!)"
    [1] => "look at JAY Z and Beyonc\303\251's page"
    [2] => "Van Jones on Bowe Bergdahl drama"    
)

我尝试了很多东西(preg_replace等),但这个正则表达式非常棘手,我无法得到我想要的结果!任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:6)

您可以将/@\[\d+:\d+:([^\]]+)\]/替换为\1

<?php

$array = array(
    "(This is so cool!)",
    "look at @[48382669205:275:JAY Z] and @[28940545600:27:Beyonc\303\251]'s page",
    "@[30042869909:32:Van Jones] on Bowe Bergdahl drama"    
);

$array = preg_replace('/@\[\d+:\d+:([^\]]+)\]/', '\1', $array);

print_r($array);

<强>输出

Array
(
    [0] => (This is so cool!)
    [1] => look at JAY Z and Beyoncé's page
    [2] => Van Jones on Bowe Bergdahl drama
)

DEMO

Regex Autopsy

Regular expression visualization

  • @ - 符号的文字
  • \[ - 一个文字[字符 - 您需要将其转义为[是一个正则表达式字符
  • \d+ - 数字匹配1到无穷大时间
  • : - 一个字面冒号
  • \d+ - 数字匹配1到无穷大时间
  • : - 一个字面冒号
  • ([^\]]+) - 一个匹配的组,匹配任何不符合文字]字符的字符匹配1到无穷大时间(意味着它匹配直到它到达] ):
  • \] - 文字]字符

答案 1 :(得分:1)

根本不是那么棘手

<?php
$array = array(
    "(This is so cool!)",
    "look at @[48382669205:275:JAY Z] and @[28940545600:27:Beyonc\303\251]'s page",
    "@[30042869909:32:Van Jones] on Bowe Bergdahl drama"    
);
$pattern = '#@\[(\d+:){2}(.*?)\]#';

$result[$k] = preg_replace($pattern, "$2", $array);