Php 用通配符替换字符串

Php 用通配符替换字符串,php,regex,str-replace,Php,Regex,Str Replace,我有一个包含多个子字符串的字符串,如我要删除的onclick=“pcm\u popup\u open(2,'Something')”。字符串中函数中的参数每次都会不同,但始终是int和string,因此也可以是onclick=“pcm\u popup\u open(1,'Something other')” 我对正则表达式的理解还不够透彻,据我所知,我不能在str_replace中使用通配符。有人能帮忙吗?谢谢。您可以用它来替换您的正则表达式匹配项 $pattern = '/(\sonclick

我有一个包含多个子字符串的字符串,如我要删除的
onclick=“pcm\u popup\u open(2,'Something')”
。字符串中函数中的参数每次都会不同,但始终是
int
string
,因此也可以是
onclick=“pcm\u popup\u open(1,'Something other')”


我对正则表达式的理解还不够透彻,据我所知,我不能在str_replace中使用通配符。有人能帮忙吗?谢谢。

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

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

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

编辑:

例如:



请注意:

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

// 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]+)\')"';

仔细观察:这似乎比它应该取代的更多,我认为正则表达式的第一次和最后一次出现之间的任何内容。在模式后放置
U
,以使匹配解除冻结:
/(\sonclick=“pcm\U popup\U open(?:*))/U'
或在通配符后使用
(?:*)
U                            # ungreedy modifier
// 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]+)\')"';