Question

I have a string that contains multiple substrings like onclick="pcm_popup_open(2, 'Something')" which I want to remove. The parameters in the function in the string will be different each time, always an int and a string though, so it could also be onclick="pcm_popup_open(1, 'Something else')".

I don't really understand regular expressions well enough, and as far as I know I can't use a wildcard in str_replace. Could someone please help? Thanks.

Was it helpful?

Solution

I don't completely get what you mean, but I can show you how to make the regex:

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

OTHER TIPS

You could use this to replace your regex matches with nothing

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

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

Idea:

(                            # 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

Edit:

U                            # ungreedy modifier

Example: https://eval.in/108780


Please note: It is not a good idea to use regex to parse HTML.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top