我真的一点都不懂正则表达式,这让我很头疼。
我有一些看起来像这样的文字
blah blah blah (here is the bit I'd like to extract)
...而且我真的不明白如何使用 PHP 的 preg_split 或等效命令来提取它。
我该怎么做呢?哪里是了解 preg 工作原理的好地方?
我真的一点都不懂正则表达式,这让我很头疼。
我有一些看起来像这样的文字
blah blah blah (here is the bit I'd like to extract)
...而且我真的不明白如何使用 PHP 的 preg_split 或等效命令来提取它。
我该怎么做呢?哪里是了解 preg 工作原理的好地方?
像这样的东西应该可以解决问题,以匹配 and 之间的(
内容)
:
$str = "blah blah blah (here is the bit I'd like to extract)";
if (preg_match('/\(([^\)]+)\)/', $str, $matches)) {
var_dump($matches[1]);
}
你会得到:
string 'here is the bit I'd like to extract' (length=35)
基本上,我使用的模式搜索:
(
; 但是由于 ( 具有特殊含义,因此必须对其进行转义:\(
[^\)]+
([^\)]+)
$matches[1]
)
;在这里,它也是一个必须转义的特殊字符:\)
<?php
$text = "blah blah blah (here is the bit I'd like to extract)";
$matches = array();
if(preg_match('!\(([^)]+)!', $text, $matches))
{
echo "Text in brackets is: " . $matches[1] . "\n";
}