This is a simplified example, but when I run this code the first does not match as it should. It only matches the first part and nothing else. The other two occurrences match properly so I have no idea why the first wouldn't.
$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) );
The results from that are:
I know 5 plus three?I know 4 and 3.What is 4 and 2.
But I'm expecting:
I know 5 and 3.I know 4 and 3.I know 4 and 2.
Hi All what you did was correct just flip the code as I have shown here.
<?
$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) );
I just flipped off the code and this is working now.
You should make global searching and as i see you changed last number word, so the code is:
/(?:What is ([\d])* plus (?:[\w]+)\?)/g
Of course you can make array of one, two, etc and replace it. Example:
$arrayN = array('one'=>1, 'two'=>2, 'three'=>'3');
Then change the expression like:
/(?:What is ([\d])* plus ([\w]+)\?)/g
and add to replace string:
I know $1 and $2 .
All word numbers change to numbers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.