0

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.

Pelin
  • 467
  • 4
  • 17

3 Answers3

1

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.

Maahly
  • 15
  • 1
  • 9
  • Thanks for quick response, I already tried that before posting the question but in scenarios like `10a.` or `10abc.` it will not only print the integer but also print `rest - 1` – Pelin Aug 05 '22 at 08:14
  • The lazy quantifier (`?`) and that second capture group are not necessary. – mickmackusa Aug 07 '22 at 04:10
0
$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.

Felix G
  • 724
  • 5
  • 17
  • Thank you @felix-g. I need to check the string before digit aswell. Is it possible to achieve with single `preg_match` or do I have to check the string first to see if it matches or not? – Pelin Aug 05 '22 at 08:25
0

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)

piotr.gradzinski
  • 873
  • 1
  • 10
  • 22