I've been trying to look around for how to select everything between two characters in a string.
Example string:
@ Some text here @
To select this I did:
/@(.*)@/
But it includes the @
signs
I tried to use different methods I found online with no success.
It sounds like you are unfamiliar with the concept of capturing groups. From "Some text here", you can extract "ex" in the middle of the word "text" using something like /t(.+)t/
. While the entire match will be "text", group #1 will be just "ex".
You can use capturing groups in PHP by passing an empty variable/empty array as the third argument to preg_match($pattern, $subject, $matches)
.
If
$matches
is provided, then it is filled with the results of search.$matches[0]
will contain the text that matched the full pattern,$matches[1]
will have the text that matched the first captured parenthesized subpattern, and so on.
What method are you working with? I'm gonna use preg_match_all
to explain two possible regular expressions
$text = "hello @this is what i want@notthis!";
if (preg_match_all("/@([^@]*)@/", $text, $results))
var_dump($results);
// [0][0] "@this is what i want@"
// [1][0] "this is what i want"
if (preg_match_all("/(?<=@)([^@]*)(?=@)/", $text, $results))
var_dump($results);
// [0][0] "this is what i want"
// [1][0] "this is what i want"
If you have multiple occurences, you can loop through the first depth. So looping through $results[1]
will always give you the correct string (since the brackets the string is in are the first in the searchable area).
As for the expressions:
The first one is the regular version. You look for a specified text (everything except @) inside specified characters. But since preg_match_all
gives you the entire string it found plus the result, you get the @ as well.
The second expression uses so called lookaround. This means the characters insdie the first and last brackets are not part of the searched area but before/behind.