x2i Posted November 30, 2010 Share Posted November 30, 2010 Hi, not sure if this is posted in the right place (think it should be in the Regex section ) 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)); Quote Link to comment https://forums.phpfreaks.com/topic/220265-preg_replace-help-extracting-an-integer/ Share on other sites More sharing options...
AbraCadaver Posted November 30, 2010 Share Posted November 30, 2010 Not sure exactly what you want to be mandatory in the matched string, but: preg_match("#\[ref=([^\]]+).*?\[/ref\]#is", $var, $matches); print_r($matches[1]); Quote Link to comment https://forums.phpfreaks.com/topic/220265-preg_replace-help-extracting-an-integer/#findComment-1141453 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.