php 正则表达式通过php获取子字符串

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

regular expression to get sub string via php

phpregexsubstring

提问by hd.

How can I use a regular expression in the substr()PHP function to get a substring matched by a pattern?

如何在substr()PHP 函数中使用正则表达式来获取与模式匹配的子字符串?

Edited:

编辑:

example:

例子:

$name = 'hello [*kitty*],how good is today';

I want to get what is between [....] placeholder.

我想得到 [ ....] 占位符之间的内容。

回答by Tim

substr()only matches whole strings. You are looking for preg_match().

substr()只匹配整个字符串。您正在寻找preg_match().

Update:

更新

$name = 'hello [*kitty*],how good is today';
preg_match( '/\[(.*?)\]/', $name, $match );
var_dump( $match );

You can find the name in $match[1]. I suggest you read up on regular expressions to understand preg_match().

您可以在$match[1]. 我建议您阅读正则表达式以了解preg_match().

回答by Mārti?? Briedis

Try this:

尝试这个:

$matches = array();
preg_match("/\[([^]]*)\]/", 'hello [*kitty*],how good is today', $matches);
print_r($matches);

Oops, fixed it now :)

哎呀,现在修好了:)