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
I don’t know about
php
, but I can provide an answer for the regex pattern.Use this:
Explanation:
(?<=[)
: lookbehind to verify that the string begins with an open bracketwork
: 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
I’m not certain of the specifics for using this in PHP, but it works in JavaScript this way.
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.
You could match
work
between the square brackets, assuming there are no occurrences of other square brackets in between.Explanation
[
Match[
K
Forget what is matched so far[^][]*
Match optional chars other than[
or]
bworkb
Match the wordwork
[^][]*
Match optional chars other than[
or]
(?=])
Positive lookahead, assert]
to the rightSee a regex101 demo.
Output