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.

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
The lazy quantifier (?) and that second capture group are not necessary.
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.

1 Comment

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?
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)

2 Comments

That s was a typo, thanks for pointing out; fixed.
And with fixed typo your code works properly, although I would go with preg_match as Felix G suggested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.