[英]php regular expression not matching correctly
這是一個簡化的示例,但是當我運行此代碼時,第一個與應有的不匹配。 它只匹配第一部分,沒有其他內容。 其他兩個匹配項正確匹配,所以我不知道為什么第一個不匹配。
$str = 'What is 5 plus three?What is 4 plus three?What is 4 plus two?';
$replacees = [
'/What is (.*?) plus two\?/',
'/What is (.*?) plus three\?/',
];
$replacers = [
'I know $1 and 2.',
'I know $1 and 3.',
];
print_r( preg_replace($replacees, $replacers, $str) );
結果是:
我知道5加3嗎?我知道4和3。什么是4和2。
但我期望:
我知道5和3.我知道4和3。我知道4和2。
嗨,所有您所做的都是正確的,只需翻轉代碼即可,如我在此處所示。
<?
$str = 'What is 5 plus three?What is 4 plus three?What is 4 plus two?';
$replacees = [
'/What is (.*?) plus three\?/',
'/What is (.*?) plus two\?/',
];
$replacers = [
'I know $1 and 3.',
'I know $1 and 2.',
];
print_r( preg_replace($replacees, $replacers, $str) );
我剛剛關閉了代碼,現在可以正常工作了。
您應該進行全局搜索,並且我看到您更改了最后一個數字字,所以代碼是:
/(?:What is ([\d])* plus (?:[\w]+)\?)/g
當然,您可以將數組1、1、2等替換為數組。 例:
$arrayN = array('one'=>1, 'two'=>2, 'three'=>'3');
然后像這樣更改表達式:
/(?:What is ([\d])* plus ([\w]+)\?)/g
並添加替換字符串:
我知道$ 1和$ 2 。
所有單詞數字都變為數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.