1.11M Members

Regex Help Requested

 
0
 

This is really a spoon feeding request. I'm in the process of learning regex, which will take time to perfect, but as of now I'm in immediate need of help to work on regex expression.

Suppose I've a string like

$str = "asggasdg46%dgeoweg5.3%sdgeoge4%kge";

In the above string, I need to extract 46, 5.3, and 4 (i.e. all ints/floating numbers preceding the % symbol)

 
1
 
(\d+(\.\d+)*?)%
 
0
 

Thanks for the reply. But using this doesn't work:

preg_match('(\d+(\.\d+)*?)%', $str, $matches);

I'm getting
Parse error: syntax error, unexpected 'preg_match' (T_STRING) in E:\xampp\htdocs\test\regex.php on line 2

 
1
 

you probably forgot a " or ; before that line.

 
0
 

My bad. So silly of me. However, I now get a different error message:
Warning: preg_match(): Unknown modifier '%'

 
0
 

Ok. I fixed the unknown modifier issue. But the output is not as expected. The output for

$str = 'asggasdg46%dgeoweg5.3%sdgeoge4%kge';
preg_match("~(\d+(\.\d+)*?)%~", $str, $matches);
pre($matches);

is

Array
(
    [0] => 46%
    [1] => 46
)

whereas it should have been

Array
(
    [0] => 46
    [1] => 5.3
    [2] => 4
)
 
0
 

But using this doesn't work

Wrong syntax. That's the problem of spoonfeeding, you get what you want, but don't know how to use it. You forgot that the regex needs to be enclosed. See the manual.

 
0
 

Yeh. I researched it and fixed the syntax issue. But the expression is not giving the expected resulted.

 
0
 

No. You're using the wrong function.

 
0
 

Well, I'm still in the learning phase. So please excuse my noobness. I tried using preg_match_all and it spat out

Array
(
    [0] => Array
        (
            [0] => 46%
            [1] => 5.3%
            [2] => 4%
        )

    [1] => Array
        (
            [0] => 46
            [1] => 5.3
            [2] => 4
        )

    [2] => Array
        (
            [0] => 
            [1] => .3
            [2] => 
        )

)

Which is very close, but repeatation ruins it.

 
0
 

repeatation ruins it.

That's a common regex issue, but array[1] returns exactly what you need, so I don't see the problem. You could use:

(\d+|\d+\.\d+)%
 
0
 

Yes it does. Thanks for the help. I'll take it up as a challenge to get familiar with regex as it will help me in the future.

Question Answered as of 1 Year Ago by pritaeas and diafol
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: