Replacing first three words

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
seamoon
Forum Newbie
Posts: 1
Joined: Sat Feb 18, 2012 12:59 pm

Replacing first three words

Post by seamoon »

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>
User avatar
ragax
Forum Commoner
Posts: 85
Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ

Re: Replacing first three words

Post by ragax »

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.
User avatar
ragax
Forum Commoner
Posts: 85
Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ

Re: Replacing first three words

Post by ragax »

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.
:)
Post Reply