0
:我如何在正則表達式中放置一個變量。在PHP中正則表達式有一些問題
事情是這樣的:
$var = "Some text";
$regular_expression = '/\d.*h/' . $var . '/hw/';
謝謝!
:我如何在正則表達式中放置一個變量。在PHP中正則表達式有一些問題
事情是這樣的:
$var = "Some text";
$regular_expression = '/\d.*h/' . $var . '/hw/';
謝謝!
這裏有兩種方法給一個變量寫入正則表達式模式的示範:
代碼:(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',
),
)
完全一樣,只是不不使用額外的分隔符。 '$ regular_expression ='/\d.*h'。 $ var。 'hw /';' – colburton
好的,謝謝colburton –