0

I'm working on a simple mention system and in my PHP script and I need to extract client:6 from the larger text where one or more @mention like @[John Doe (#6)](client:6) will be present.

Ex. This is my text how do you like it @John and do you have any thoughts @Jane

In php the string will look like.

This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)

and i need to get an array with array('client:6','client:7')

1
  • Yes a lot on regex101.com, but i don't know how it works so i'm just guessing and getting no where. Commented Nov 20, 2021 at 14:05

2 Answers 2

2

One of many possible ways would be

@\[[^][]+\]\s*\(\K[^()]+

See a demo on regex101.com.


In terms of regular expressions, this boils down to

@          # "@" literally
\[         # "[" literally
[^][]+     # not "[" nor "]" as many times as possible
\]\s*      # followed by "]" literally + whitespaces, eventually
\(         # you name it - "(" literally
\K         # forget all what has been matched that far
[^()]+     # not "(" nor ")"

In PHP this could be

<?php

$data = "This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)";

$regex = "~@\[[^][]+\]\s*\(\K[^()]+~";

preg_match_all($regex, $data, $matches);

print_r($matches);

?>

And would yield

Array
(
    [0] => Array
        (
            [0] => client:6
            [1] => client:7
        )

)

See a demo on ideone.com.

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

1 Comment

This seems to be working nicely on your demo. I'll test it out.
1

\w+:\d+ should work.

In the sentence :

This is my text how do you like it @John Doe (#6) and do you have any thoughts @Jane Doe (#7)

It should find client:6 and client:7 .

You can try your regex live using https://regexr.com/ for example.

2 Comments

Cool that works, but how to make it a bit better so it will only catch entries that begins with @. Just so it won't catch if i just write client:10 with out writing @[John Smith](client:10).
It could also be an idea to first get an array of all @ like array('@[John Smith](client:10)',@[Jane Smith](client:12)) and loop through them to get the specific client:10

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.