1

i have a string like this:

"bla blabla bla bla [bla:bla:bla] blabla blablabla [ble:ble:ble] bla bla bla"

What i need is to find if theres a "[*:*:*]" in my string and get the content. From that i think i know how to replace it.

For a better explanation, the string is a description of something, and between the "[]" theres some parameteres to build an url, so there can be any number of "[]" in my string and i need the content as this the info needed to build the url.

Thanks in advance!

2
  • You need only if there are [*:*:*] what if there are more than two i.e [*:*:*:*:*] Commented Jul 23, 2019 at 17:20
  • I got the [(.*?)] (actually i got the "/[[^]]*]/") but the problem is that regex will capture things like [text] that i dont want. The match has to be with the format [::*]. There are always 3 substrings in that. Commented Jul 23, 2019 at 17:26

1 Answer 1

2

You might use \G to assert the position at the end of the previous match and capture what is between : in a capturing group:

(?:\[|\G(?!\A))([^:\][]+)(?::|\])
  • (?: Non capturing group
    • \[ Match [
    • | Or
    • \G(?!\A) Assert position at the end of previous match, not at the start
  • ) Close non capturing group
  • ( Capture group 1
    • [^:\][]+ match 1+ times any char except the listed in the character class
  • ) close group 1
  • (?::|\]) Match either : or ]

Regex demo

Or use preg_match_all and array_map to match the 3 substrings between [*:*:*] to get all the values:

$pattern = "/\[((?:[^:]+:){2}[^:]+)\]/";
$str = "bla blabla bla bla [bla:bla:bla] blabla blablabla [ble:ble:ble] bla bla bla";

preg_match_all($pattern, $str, $matches);

$result = array_map(function($x) {
    return explode(':', $x);
}, $matches[1]);

print_r($result);

Result

Array
(
    [0] => Array
        (
            [0] => bla
            [1] => bla
            [2] => bla
        )

    [1] => Array
        (
            [0] => ble
            [1] => ble
            [2] => ble
        )

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

1 Comment

I think preg_replace_callback is used for search and replacing but I think the OP wants the parts between to build a url that is why I chose preg_match_all. If you pass a string to preg_replace_callback, then a string is also returned and then you still have to get the separate parts.

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.