0

在 PHP 中,我有这样的字符串:

$string = "This is a 123 test (your) string (for example 1234) to test.";

从那个字符串中,我想用数字获取 () 内的单词。我尝试过使用explode,但由于括号中包含2个单词/字符串组,我最终得到(你的)而不是(例如1234)。我也像这样使用 substr :

substr($string, -20)

这在大多数情况下都有效,但问题是,在某些情况下字符串较短,因此最终会得到不需要的字符串。我也尝试过使用正则表达式,我在其中设置了如下内容:

/[^for]/

但这也不起作用。我想得到的字符串总是以“for”开头,但长度会有所不同。如何操作 php 以便我只能获取括号内以 for 开头的字符串?

4

4 回答 4

3

在这种情况下,我可能会使用 preg_match() 。

preg_match("#\((for.*?)\)#",$string,$matches);

找到的任何匹配项都将存储在 $matches 中。

于 2013-10-03T01:09:54.597 回答
2

使用以下正则表达式:

(\(for.*?\))

它将捕获以下模式:

(for)
(foremost)
(for example)
(for 1)
(for: 1000)

一个示例 PHP 代码:

$pattern = '/(\(for.*?\))/';
$result  = preg_match_all( 
    $pattern, 
    " text (for example 1000) words (for: 20) other words",
    $matches 
);

if ( $result > 0 ) {
    print_r( $matches );
}


以上print_r( $matches )结果:

Array
(
    [0] => Array
        (
            [0] => (for example 1000)
            [1] => (for: 20)
        )

    [1] => Array
        (
            [0] => (for example 1000)
            [1] => (for: 20)
        )
)
于 2013-10-03T01:09:49.590 回答
1

使用preg_match进行正则表达式

$matches = array();
$pattern = '/^for/i';
preg_match($pattern,$string,$matches);
pirnt_r($matches);

如果matches提供,则填充搜索结果。$matches[0]将包含与完整模式匹配的$matches[1]文本,将具有与第一个捕获的带括号的子模式匹配的文本,依此类推。

于 2013-10-03T01:13:54.533 回答
0
$matches = array(); 
preg_match("/(\(for[\w\d\s]+\))/i",$string,$matches);
var_dump($matches);
于 2013-10-03T01:16:45.827 回答