Reputation: 716
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.
Upvotes: 0
Views: 49
Reputation: 950
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.
Upvotes: 2
Reputation: 63
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.
Upvotes: 1