1

给大家一个简单的问题。对不起,我不得不问它。

在我的网站上,我想在文本中的“随机”位置使用签名。问题是,这个给定的字符串中可能有多个不同的签名。

签名代码是~~USERNAME~~

所以像

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

我试过用preg_match这个,没有成功。我知道第三个参数用于存储匹配项,但由于格式的原因,我无法正确获取匹配项。

我应该不使用preg_match,还是我不能以这种方式使用签名?

4

2 回答 2

6

您可以使用preg_match_all并使用此修改regex

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

在此处输入图像描述

编码...

<?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
)
于 2014-02-23T01:55:40.813 回答
4

这应该有效,但用户名不得包含~~

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

输出:

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

第一个子数组包含完整匹配的字符串,其他子数组包含匹配的组。


您可以使用标志更改顺序PREG_SET_ORDER,请参阅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);

此代码产生以下输出

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
        )
)
于 2014-02-23T01:57:08.017 回答