php 正则表达式,获取两个字符之间的字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2034687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:44:49  来源:igfitidea点击:

Regex, get string value between two characters

phpregex

提问by Johannes

I'd like to return string between two characters, @ and dot (.).

我想返回两个字符之间的字符串,@ 和点 (.)。

I tried to use regex but cannot find it working.

我尝试使用正则表达式,但找不到它的工作原理。

(@(.*?).)

Anybody?

有人吗?

回答by Mark Byers

Your regular expression almost works, you just forgot to escape the period. Also, in PHP you need delimiters:

您的正则表达式几乎有效,您只是忘记转义句号。另外,在 PHP 中你需要分隔符:

'/@(.*?)\./s'

The s is the DOTALL modifier.

s 是DOTALL 修饰符

Here's a complete example of how you could use it in PHP:

这是一个关于如何在 PHP 中使用它的完整示例:

$s = '[email protected]';
$matches = array();
$t = preg_match('/@(.*?)\./s', $s, $matches);
print_r($matches[1]);

Output:

输出:

bar

回答by Gumbo

Try this regular expression:

试试这个正则表达式:

@([^.]*)\.

The expression [^.]*will match any number of any character other than the dot. And the plain dot needs to be escaped as it's a special character.

该表达式[^.]*将匹配除点以外的任意数量的任何字符。普通点需要转义,因为它是一个特殊字符。

回答by Geert

If you're learning regex, you may want to analyse those too:

如果您正在学习正则表达式,您可能也想分析这些:

@\K[^.]++(?=\.)

(?<=@)[^.]++(?=\.)

Both these regular expressions use possessive quantifiers (++). Use them whenever you can, to prevent needless backtracking. Also, by using lookaround constructions (or \K), we can match the part between the @and the .in $matches[0].

这两个正则表达式都使用所有格量词 ( ++)。尽可能使用它们,以防止不必要的回溯。此外,通过使用环视结构(或\K),我们可以匹配in@.in之间的部分$matches[0]

回答by Dièse

this is the best and fast to use

这是最好的和快速的使用

function get_string_between ($str,$from,$to) {

    $string = substr($str, strpos($str, $from) + strlen($from));

    if (strstr ($string,$to,TRUE) != FALSE) {

        $string = strstr ($string,$to,TRUE);

    }

    return $string;

}