Question

Simple question for you folks. Sorry that I have to ask it.

On my website, I want to use signatures at "random" places in my text. The problem is, There could be multiple DIFFERENT signatures in this given string.

The signature code is ~~USERNAME~~

So anything like

~~timtj~~
~~foobar~~
~~totallylongusername~~
~~I-d0n't-us3-pr0p3r-ch@r@ct3r5~~

I have tried using preg_match for this, with no success. I understand that the third parameter is used to store the matches, but I can not properly get a match because of the format.

Should I not use preg_match, or am I just not able to use signatures in this manner?

Was it helpful?

Solution

You could make use of preg_match_all and with this modified regex

preg_match_all('/~~(.*?)~~/', $str, $matches);

enter image description here

The code...

<?php
$str="~~I-d0n't-us3-pr0p3r-ch@r@ct3r5~~";
preg_match_all('/~~(.*?)~~/', $str, $matches);
print_r($matches[1]);

OUTPUT :

Array
(
    [0] => I-d0n't-us3-pr0p3r-ch@r@ct3r5
)

OTHER TIPS

This should work, but usernames mustn't contain ~~

preg_match_all('!~~(.*?)~~!', $str, $matches);

Output:

Array
(
    [0] => Array
        (
            [0] => ~~timtj~~
            [1] => ~~foobar~~
            [2] => ~~totallylongusername~~
            [3] => ~~I-d0n't-us3-pr0p3r-ch@r@ct3r5~~
        )


    [1] => Array
        (
            [0] => timtj
            [1] => foobar
            [2] => totallylongusername
            [3] => I-d0n't-us3-pr0p3r-ch@r@ct3r5
        )
)

The first sub array contains the complete matched strings and the other sub arrays contain the matched groups.


You could change the order by using the flag PREG_SET_ORDER, see http://php.net/preg_match_all#refsect1-function.preg-match-all-parameters

<?php
$str = "~~timtj~~ ~~foobar~~ ~~totallylongusername~~ ~~I-d0n't-us3-pr0p3r-ch@r@ct3r5~~";
preg_match_all("!~~(.*?)~~!", str, $matches, PREG_SET_ORDER);
print_r($matches);

This code produces the following output

Array
(
    [0] => Array
        (
            [0] => ~~timtj~~
            [1] => timtj
        )

    [1] => Array
        (
            [0] => ~~foobar~~
            [1] => foobar
        )

    [2] => Array
        (
            [0] => ~~totallylongusername~~
            [1] => totallylongusername
        )

    [3] => Array
        (
            [0] => ~~I-d0n't-us3-pr0p3r-ch@r@ct3r5~~
            [1] => I-d0n't-us3-pr0p3r-ch@r@ct3r5
        )
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top