簡體   English   中英

字符長度未知的正則表達式

[英]Regex with unknown character length

你們這個簡單的問題。 對不起,我得問一問。

在我的網站上,我想在文本的“隨機”位置使用簽名。 問題是,在此給定的字符串中可能有多個DIFFERENT簽名。

簽名代碼是~~USERNAME~~

所以像

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

我嘗試為此使用preg_match ,但沒有成功。 我知道第三個參數用於存儲匹配項,但是由於格式原因,我無法正確獲取匹配項。

我應該不使用preg_match ,還是不能以這種方式使用簽名?

您可以使用preg_match_all以及此修改后的regex

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

enter image description here

編碼...

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

這應該可以,但是用戶名不能包含~~

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM