Home > Back-end >  PHP preg_replace get only specific integer part
PHP preg_replace get only specific integer part

Time:08-06

I have set of static string set with different integer values. I am trying to get only the part I need using preg_replace. But the thing is whenever I get the number, it also returns the part after that aswell.

Example strings;

$str = "Increase weather temp by up to 10.";
$str2 = "Increase weather temp by up to 10abc 123 def.";
$str3 = "Increase weather temp by up to 10 12 14.";

Desired output for examples above;

10

My code;

preg_replace('/^Increase weather temp by up to (\d )/', '$1', $str)

I also tried ~ but it didnt help me to solve the issue aswell. Whenever I test this regex through testers, it works fine;

Is there any part I am missing? Thanks in advance.

CodePudding user response:

Your regex only matches the text (Increases weather...) closed by a number. So preg_replace replaces only this part with the first group. If you want to replace the whole string, even after the number, use

preg_replace('/^Increases weather temp by up to (\d )(. ?)/', '$1', $str)

instead. The ( .?) causes the PHP to replace everything after your number too.

CodePudding user response:

$str = "Increases weather temp by up to 10.";
$str2 = "Increase weather temp by up to 10abc 123 def.";
$str3 = "Increase weather temp by up to 10 12 14.";

preg_match("/\d /", $str, $m);
var_dump($m[0]);

preg_match("/\d /", $str2, $m2);
var_dump($m2[0]);

preg_match("/\d /", $str3, $m3);
var_dump($m3[0]);

You can also use preg_match to get an array of matching strings and pick the respective element from that array.

CodePudding user response:

True root cause of this is that you have different texts:

$str = "Increases weather temp by up to 10.";
$str2 = "Increase weather temp by up to 10abc 123 def.";
$str3 = "Increase weather temp by up to 10 12 14.";

"Increases", "Increase", "Increase" - the other two don't have 's' at the end.

and in preg_replace:

preg_replace('/^Increases weather temp by up to (\d )/', '$1', $str)

  • Related