Jump to content

Preg_Replace Help - Extracting an integer


x2i

Recommended Posts

Hi, not sure if this is posted in the right place (think it should be in the Regex section  :shrug:) but hopefully someone can help me out a bit.

 

I have the following string for example which is stored in a variable called $var.

 

This is a reference [ref=17][/ref] number

 

I wish to extract only the number after the equals sign and store it as a variable. So I am using the following code to do so:

 

$ref_num = preg_replace("/.*?\[ref\=(.*?)\]\[\/ref\].*?/is", "$1", $var);

 

The only problem is, I can omit the text before the integer and the tags themselves but I still get the text after the [/ref] section and I cannot get rid of it. It seems my .*? placed after it doesn't work like it does at the beginning.

 

Can anyone offer any help at all, it will be greatly appreciated - I'm fairly new to using Preg_replace so I still don't know how best to form Regular Expressions.

 

Thanks, Dan

 

 

EDIT-

I have found a workaround which I will post below - however I would still like to solve it the way I planned originally which is the way I posted here. Here's what I did - because I know the integer is never going to be more than 5 characters long, I used the replace from before but added a substring like so.

 

$ref = substr(preg_replace("/.*?\[ref\=(.*?)\]\[\/ref\]/is", "$1", $var),0,5);

 

This grabbed the first 5 characters whether it was a number or not, then I used this to strip any non-numerical characters. Finally I added an intval to convert it to an integer rather than a string.

 

$ref = intval(preg_replace ('/[^\d\s]/', '', $ref));

Link to comment
https://forums.phpfreaks.com/topic/220265-preg_replace-help-extracting-an-integer/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.