0

I have a string:

   $str =  'title="favorite" name="fav_1" onclick="return ..."'

I want to replace name to class and stripe onclick attribute.

What I have tried ?:


    $str = 'title="favorite" name="fav_12" onclick="return.."';

    $replace = str_replace('name', 'class', $str);

Humm.. its okey. what is your problem ?


If I use str_replace then I need to repeat this step two time, first for replacing name to class and second stripe onclick to blank space.

Repeating code is not a problem, but str_replace will not work If I dont know what is inside onclick="...".

So please suggest how do I replacing name to class and stripping onclick just in single line of code.

user007
  • 3,203
  • 13
  • 46
  • 77

2 Answers2

2

The simplest way would be to use:

preg_replace('/onclick=".*"/', '', $str);

But you should look into a DOM parser, as the above would probably break at some point.

Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
  • @user007 any reason you're ignoring [this answer](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)? – Kermit Sep 18 '13 at 12:23
  • No I am not ignoring this answer :-) – user007 Sep 18 '13 at 12:26
1

A simple solution would be:

$str = preg_replace('/onclick="([^"]+)"/', ' ', $str);

But if there are some quotes inside the onclick quotes, it'll fail (even if they're escaped with \).

h3llb0y
  • 11
  • 1