skip to Main Content

So I want to get the text within the square brackets(without brackets) if a keyword is matched within the brackets.

so the keyword works but for example "test [work all day] test" it returns everything in the brackets and outside as well .

so far i have the below, but I only want it to return everything within the brackets(without bracekts) if the keyword "work" is matched within the brackets.

preg_match('/.*([work.*?]).*/', $res, $match)

3

Answers


  1. I don’t know about php, but I can provide an answer for the regex pattern.

    Use this:

    (?<=[)work[^]]*
    

    Explanation:

    • (?<=[): lookbehind to verify that the string begins with an open bracket
    • work: literal match
    • [^]]*: negated character class with * quantifier which matches every other character except a closed bracket (the first closed bracket is escaped)

    Now, you get a string which is preceded with an open bracket, and is matched up to the point before the closing bracket.

    Verify here

    Login or Signup to reply.
  2. I’m not certain of the specifics for using this in PHP, but it works in JavaScript this way.

    let src = "test [work all day] test"
    console.log(src.replace( /.*[(work.*?)].*/g, "$1"));
    

    Please put the part you want to extract in parentheses and replace the entire string with $1.

    $1 refers to the contents of the first parenthesis.
    It will be helpful for you.

    Login or Signup to reply.
  3. You could match work between the square brackets, assuming there are no occurrences of other square brackets in between.

    [K[^][]*bworkb[^][]*(?=])
    

    Explanation

    • [ Match [
    • K Forget what is matched so far
    • [^][]* Match optional chars other than [ or ]
    • bworkb Match the word work
    • [^][]* Match optional chars other than [ or ]
    • (?=]) Positive lookahead, assert ] to the right

    See a regex101 demo.

    $res = "test [work all day] test";
    $pattern = '/[K[^][]*bworkb[^][]*(?=])/';
    
    if (preg_match($pattern, $res, $match)) {
        echo $match[0];
    }
    

    Output

    work all day
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search