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

时间:2023-01-21 15:24:21

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.

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

2 个解决方案

#1


35  

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()。

#2


4  

Try this:

尝试这个:

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

Oops, fixed it now :)

哎呀,现在修好:)

#1


35  

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()。

#2


4  

Try this:

尝试这个:

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

Oops, fixed it now :)

哎呀,现在修好:)