2

I have an array $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"    
)

I want to match delete the @[0-9] text, so my output looks like:

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

I tried a whole bunch of things (preg_replace, etc) but this regex is so tricky I can't get the result I want! Any help is appreciated.

0

2 Answers 2

6

You can replace /@\[\d+:\d+:([^\]]+)\]/ with \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);

Output:

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

  • @ - a literal at sign
  • \[ - a literal [ character - you need to escape it as [ is a regex character
  • \d+ - a digit matched 1 to infinity times
  • : - a literal colon sign
  • \d+ - a digit matched 1 to infinity times
  • : - a literal colon sign
  • ([^\]]+) - a matching group matching any character that isn't a literal ] character matched 1 to infinity times (meaning it will match until it hits a ]):
  • \] - a literal ] character
Sign up to request clarification or add additional context in comments.

9 Comments

See needed [1] => "look at JAY Z and Beyonc\303\251's page"
@Brotheyura That's just because escaped characters in " are expanded.
+1, withdrew my answer as I hadn't read the question correctly. No need to duplicate your great work. :)
array_map is not mandatory, preg_replace works with arrays. Nevertheless +1.
@M42 Good call - there's absolutely no reason for array_map in this code then.
|
1

Not that tricky at all

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

1 Comment

preg_replace can operate on arrays and return an array. Using an array rather than a for loop involves less code and runs faster, hence my -1

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.