简体   繁体   中英

Searching & Replacing first characters of an expression in Notepad++ using regular expression

I want to replace the "<p>" tag with "<p class="myclass">" class in the following html with Search & Replace (using regular expression) function in Notepad++

<p><?php echo $element_arr["a1_discount"]; ?></p>
<p><?php echo $element_arr["b2_discount"]; ?></p>
<p><?php echo $element_arr["c5_discount"]; ?></p>

I was able to match the above with the following reg-ex:

RegEx: (<p><\?php echo \$element_arr\["[A-Za-z][1-99]_discount"\]; \?>)

I tried the following replace reg-ex but it's not working:

(<p class="myclass"><\?php echo \$element_arr\["[A-Za-z][1-99]_discount"\]; \?>)

It comes out as: <p class="cool"><?php echo $element_arr["[A-Za-z][1-99]_discount"]; ?></p> <p class="cool"><?php echo $element_arr["[A-Za-z][1-99]_discount"]; ?></p>

Can someone help me with this. This will be a huge time-saver as I have lots of editing of such nature to do.

Thanks a lot

dkj

You don't even need a regex for this. Just search for

<p> and replace it with <p class="myclass">

In case you do have other p tags with various attributes, you can use the following approach:

  1. Run the S&R with (<p[^<>]*\\bclass=")[^"]*("[^<>]*>) regex replacing with $1myclass$2 (the Regular Expression option ON).

This is working for strings like

<p class="someclass">text</p>
<p id="new" class="someclass">text</p>
<p id="new" class="someclass" end="true">text</p></code>
  1. Run the S&R with <p\\b(?![^<>]*\\bclass=)([^<>]*)> replacing with <p$1 class="myclass"> for paragraph tags without attributes or without class attribute.

This is fine for strings like

<p>text</p>
<p id="new">text</p>

This complexity can be easily removed if you decided to use any HTML parser with a regular programming language.

How about:

Find what: <p>(?=<\\?php echo \\$element_arr\\["[A-Za-z][1-9][0-9]*_discount"\\]; \\?>)
Replace with: <p class="myclass">

Where (?=...) is a positive lookahead that makes sure you have <?php echo ... after the tag <p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM