php 如何在 preg_match 中使用可变模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1386748/
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 02:20:31  来源:igfitidea点击:

How do I use a variable pattern with preg_match?

phpregexpreg-match

提问by homework

I don't know if this is enough data to feed off of, but I have

我不知道这是否足以提供足够的数据,但我有

preg_match('/SAMPLETEXT/', $bcurl, $cookie1);

preg_match('/SAMPLETEXT/', $bcurl, $cookie1);

and I was wondering if I can make it

我想知道我能不能做到

preg_match($newfunction, $bcurl, $cookie1);

preg_match($newfunction, $bcurl, $cookie1);

but when I do, I get this error "Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in".

但是当我这样做时,我收到此错误“警告:preg_match() [function.preg-match]:分隔符不能是字母数字或反斜杠”。

How can I make it check for my new function, rather than have it check just for "SAMPLETEXT".

我怎样才能让它检查我的新功能,而不是让它只检查“SAMPLETEXT”。

回答by ysth

Try preg_match("/$newfunction/", $bcurl, $cookie1);so that you are providing the required delimiters (using a delimiter that isn't going to be in $newfunction).

尝试preg_match("/$newfunction/", $bcurl, $cookie1);提供所需的分隔符(使用不在 $newfunction 中的分隔符)。

But note that the documentationsays "Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster."

但请注意,文档说“如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用 preg_match()。使用 strpos() 或 strstr() 代替,因为它们会更快。”

回答by Vincent

preg_match('/'.$pattern.'/i', $subject)

preg_match('/'.$pattern.'/i', $subject)

ioption: allow capital letters or hyphen.

i选项:允许大写字母或连字符。

回答by r7eem

u can use variable by putting it between []

您可以通过将变量放在 [] 之间来使用它

    $subject = "abcdef";
$ch = 'b';
$pattern = '/[$ch]/';
preg_match($pattern, $subject, $matches);
//print_r($matches);
if ($matches)
{
    echo $subject;
}