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)

Edited by asprin

3
Contributors
11
Replies
26
Views
4 Years
Discussion Span
Last Post by asprin
Featured Replies
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

Edited by asprin

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 '%'

Edited by asprin

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

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+)%

Edited by pritaeas

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.