正则表达式有一些问题

时间:2017-07-18 18:41:19

标签: php preg-match-all

PHP中的

:如何将变量放在正则表达式中。

这样的事情:

$var = "Some text";
$regular_expression = '/\d.*h/' . $var . '/hw/';

谢谢!

1 个答案:

答案 0 :(得分:0)

以下是将变量写入正则表达式模式的两种方法的演示:

代码:(Demo Link

$string='8_hSome texthw 9_hSome texthw';
$var = "Some text";

//Single quoted pattern with dot-concatenation:
$regex1= '/\d.*h' . $var . 'hw/';
var_export(preg_match_all($regex1,$string,$out)?$out:'failed');

echo "\n---\n";

// Double quoted pattern with curly bracketed variable isolation:
$regex2= "/\d.*h{$var}hw/";
var_export(preg_match_all($regex2,$string,$out)?$out:'failed');

// note the greedy quantifier (*) matches 1 long substring, instead of two short substrings

输出:

array (
  0 => 
  array (
    0 => '8_hSome texthw 9_hSome texthw',
  ),
)
---
array (
  0 => 
  array (
    0 => '8_hSome texthw 9_hSome texthw',
  ),
)