[英]Select everything between two characters without including them
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/
. 您可以使用
/t(.+)t/
东西,从“此处的某些文本”中提取“文本”中间的“ ex”。 While the entire match will be "text", group #1 will be just "ex". 虽然整个比赛都是“文字”,但第1组只是“ 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)
. 通过将空变量/空数组作为第三个参数传递给
preg_match($pattern, $subject, $matches)
可以在PHP中使用捕获组。
If
$matches
is provided, then it is filled with the results of search.如果提供了
$matches
,则将其填充为搜索结果。$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.$matches[0]
将包含与完整模式匹配的文本,$matches[1]
将具有与第一个捕获的带括号的子模式$matches[1]
的文本,依此类推。
What method are you working with? 您使用什么方法? I'm gonna use
preg_match_all
to explain two possible regular expressions 我将使用
preg_match_all
解释两个可能的正则表达式
$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). 因此,循环遍历
$results[1]
将始终为您提供正确的字符串(因为该字符串所在的括号是可搜索区域中的第一个括号)。
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. 但是由于
preg_match_all
会为您提供找到的整个字符串以及结果,因此您也将获得@。
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.
这意味着插入和插入括号的字符不是搜索区域的一部分,而是之前/之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.