PHP用通配符替换字符串

时间:2014-03-03 20:52:37

标签: php regex str-replace

我有一个包含多个子字符串的字符串,例如我要删除的onclick="pcm_popup_open(2, 'Something')"。字符串中函数中的参数每次都不同,但总是intstring,所以它也可能是onclick="pcm_popup_open(1, 'Something else')"

我不太了解正则表达式,据我所知,我不能在str_replace中使用通配符。有人可以帮忙吗?感谢。

2 个答案:

答案 0 :(得分:0)

你可以用它来替换你的正则表达式匹配

$pattern = '/(\sonclick="pcm_popup_open(?:.*)")/U';

echo preg_replace($pattern, "", $test); // replace with nothing

点子:

(                            # capture group open
    \s                       # match the space before "onclick"
    onclick="pcm_popup_open  # match that text
    (?:                      # open non-capture group
        .*                   # match anything
    )                        # close non-capture group
    "                        # match the closing onclick attribute
)                            # close capture group

编辑:

U                            # ungreedy modifier

示例:https://eval.in/108780


请注意: It is not a good idea to use regex to parse HTML.

答案 1 :(得分:0)

我不完全明白你的意思,但我可以告诉你如何制作正则表达式:

// step1: take the string, and escape it (hint: there's a function for this)
$regex = 'onclick="pcm_popup_open\(2, \'Something\'\)"';

// step2: replace the number, you can limit it with: {minLength,maxLength}
$regex = 'onclick="pcm_popup_open(([0-9]){1,}, \'Something\')"';

// step3: replace the string
$regex = 'onclick="pcm_popup_open(([0-9]){1,}, \'(a-zA-Z0-0]+)\')"';