有关正则表达式的帮助,变量不会在模式中扩展

时间:2011-02-16 12:15:21

标签: php regex

代码:

$source = file_get_contents('http://php.about.com/od/learnphp/qt/hello_world.htm');
$test_var = "hello world";
$pattern = "|<h[^>]+>($test_var)</[^>]+>|i";
echo $pattern;

$test = preg_match_all($pattern,$soure,$matches);

输出:

|]+>(  )]+>|i
ArrayArrayArray ( [0] => Array ( ) [1] => Array ( ) ) 

1 个答案:

答案 0 :(得分:2)

尝试:

// match all headings
$pattern = "|<h[^>]+>([^>]+)<\/h[^>]+>|i";

// match heading containing "hello world"
$test_var = "hello world";
$pattern = "|<h[^>]+>(" . $test_var . ")</h[^>]+>|i";

示例:

php > $source = file_get_contents('http://php.about.com/od/learnphp/qt/hello_world.htm');
php > $pattern = "|<h[^>]+>([^>]+)<\/h[^>]+>|i";
php > preg_match_all($pattern, "<h1>hello world</h1>", $matches);

虽然从我能辨别的内容来看,您发布的代码不应该存在问题。 究竟是什么问题/问题?