Any questions involving matching text strings to patterns - the pattern is called a "regular expression."
Moderator: General Moderators
seamoon
Forum Newbie
Posts: 1 Joined: Sat Feb 18, 2012 12:59 pm
Post
by seamoon » Sat Feb 18, 2012 1:02 pm
Hi I want to replace first three "Next" words to "Previous" as I shown below, I tried some tools but I couldn't what regexes should I use to do this?
Code: Select all
<li style="margin-right: 20px;">
<a href="4.html" title="Next">
<img src="../thumbs/4.JPG" alt="Next" />
<h2>Next</h2>
<div class="clear"></div>
</a>
</li>
<li style="margin-left: 20px;">
<a href="6.html" title="Next">
<img src="../thumbs/6.JPG" alt="Next" />
<h2>Next</h2>
to this:
Code: Select all
<li style="margin-right: 20px;">
<a href="4.html" title="Previous">
<img src="../thumbs/4.JPG" alt="Previous" />
<h2>Previous</h2>
<div class="clear"></div>
</a>
</li>
<li style="margin-left: 20px;">
<a href="6.html" title="Next">
<img src="../thumbs/6.JPG" alt="Next" />
<h2>Next</h2>
ragax
Forum Commoner
Posts: 85 Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ
Post
by ragax » Sat Feb 18, 2012 1:38 pm
Hi Seamoon!
1. Run this:
Code:
Code: Select all
<?php
$string='<li style="margin-right: 20px;">
<a href="4.html" title="Next">
<img src="../thumbs/4.JPG" alt="Next" />
<h2>Next</h2>
<div class="clear"></div>
</a>
</li>
<li style="margin-left: 20px;">
<a href="6.html" title="Next">
<img src="../thumbs/6.JPG" alt="Next" />
<h2>Next</h2>';
$regex=',(?s)^(?>.*?\b\K(Next))\b(?>(.*?)\b(Next))\b(.*?)\bNext\b,';
$replace='Previous\2Previous\4Previous';
$string=preg_replace($regex,$replace,$string,1);
echo htmlentities($string);
?>
Output:
[text]<li style="margin-right: 20px;"> <a href="4.html" title="Previous"> <img src="../thumbs/4.JPG" alt="Previous" /> <h2>Previous</h2> <div class="clear"></div> </a> </li> <li style="margin-left: 20px;"> <a href="6.html" title="Next"> <img src="../thumbs/6.JPG" alt="Next" /> <h2>Next</h2>[/text]
2. Please don't cross-post .
Hope this works for you, let me know if you have any questions.
Wishing you a fun weekend.
ragax
Forum Commoner
Posts: 85 Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ
Post
by ragax » Sat Feb 18, 2012 4:54 pm
Hi again,
I know from the other post that your problem is now solved.
But in hindsight and for the record for the php solution: now that I'm awake, I see that I could have made the solution much simpler by using "3" as the fourth argument in the preg_replace, so that we simply replace Next three times.
Code: Select all
$string=preg_replace(',\bNext\b,','Previous',$string,3);
It's one of those times when I jump to the complicated.