handypam
asked on
PHP Preg_replace with a * in the pattern
Hello experts.
I have a small bit of code...
ix="3,*"
and i am trying to do a simple preg_replace so that it becomes
ix="3,3"
Basically whatever the first item is i want it to replace the star.
I think the star is causing me issues as i cant get anything to work.
Any help would be gratefully accepted ...
thanks
I have a small bit of code...
ix="3,*"
and i am trying to do a simple preg_replace so that it becomes
ix="3,3"
Basically whatever the first item is i want it to replace the star.
I think the star is causing me issues as i cant get anything to work.
Any help would be gratefully accepted ...
thanks
Here you go, a better example
produces
Here is a test 3,3 string
<?php
$pattern = '#(3),(\*)#';
$data = "Here is a test 3,* string";
echo preg_replace( $pattern, '$1,$1', $data );
produces
Here is a test 3,3 string
ASKER
Thank you for your help so far.
The code works in isolation but you look at this test
It really does strange things to the string....
Any more help would get a huge :D from me... thanks in advance
The code works in isolation but you look at this test
It really does strange things to the string....
Any more help would get a huge :D from me... thanks in advance
<?php
$test = 'test test ix="2,*" test test ix="3,*" test test ix="4,*" test test';
$i=0;
$find[$i]='#ix="(.*),(\*)"#';
$replace[$i]='ix="$1,$1"';
echo "<br>Before:".$test;
$t = preg_replace($find, $replace, $test);
echo "<br>After:".$t;
?>
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Oh - it was a HUGE :D not a HUG..... I misread it.
My apologies.....
:-O
My apologies.....
:-O
ASKER
Hurray it works
Faith in mankind = RESTORED!
Hugz + points
Faith in mankind = RESTORED!
Hugz + points
Glad you're sorted. Thanks for the hugz as well as the points
:-D
One additional note - regex is greedy and will match as much as possible to a pattern like .* but you can tell it not to be greedy by using .*? so in your pattern I could have used
$find[$i]='#ix="(.*?),(\*) "#';
but if that test is always a number then it is safer to be specific which is why I replaced .* with [0-9]*
:-D
One additional note - regex is greedy and will match as much as possible to a pattern like .* but you can tell it not to be greedy by using .*? so in your pattern I could have used
$find[$i]='#ix="(.*?),(\*)
but if that test is always a number then it is safer to be specific which is why I replaced .* with [0-9]*
$pattern = '3,\*';