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)

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

Member Avatar for diafol

you probably forgot a " or ; before that line.

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

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
)

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.

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

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.

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.