?
Solved

Need assistance with For Each loop

Posted on 2015-01-03
12
Medium Priority
?
93 Views
Last Modified: 2016-11-16
I am trying to create a for each loop on this preg match.    This works great.  Just needs to pick up several options.


//OPTIONS		
//NEED LOOP HERE	 

preg_match('%<option value="(.*?)">(.*?)<\/option>%',$buffer,$matches6);
  
        $option1=$matches6[2];
		
echo $option1."<BR>";

Open in new window

0
Comment
Question by:lawrence_dev
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
12 Comments
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40529750
This should work I think:
preg_match_all('%<option value="(.*?)">(.*?)<\/option>%',$buffer,$matches6);
$options = $matches6[2];
foreach ($options as $option) {
  echo $option."<BR>";
}

Open in new window

(Edit: changes $matches6[1] to $matches6[2])
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40530110
No points for this, please.  I think @Terry Woods has given you a pretty good answer.  But from the look of this and your other questions it almost seems like you're trying to learn PHP by trial and error, copying fragments of code you've found on the internet.  That is a very long and slow process with an uncertain outcome.  I'd like to lead you to some better learning resources.  In particular, this article will help you get a good foundation.  The resources in it are vetted by the PHP community and are worthy of your time and attention.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

One of the practices I follow whenever I have to explore a new piece of technology is the practice of setting up a teaching example.  Since I've been doing this for a few years, I have a robust teaching library.  Here's a sample, drawn from your question.  It has references and links to the associated documentation, and comments that (hopefully) make sense for the context of learning regular expression matching and using matched data with iterators.  Here are a few notes...

Line 7: Use this always without fail.  Absent correct error_reporting() settings, PHP may allow your script to rely on an undefined variable.  A typographical error can be devilishly hard to find without full error reporting.

Line 19: Notice the way that the regular expression is written in a string concatenation.  This makes it very easy to modify the regex and add comments without disrupting the other parts of the string.

Line 21, 25: You probably want to look this function up and understand its action.  If you use it regularly you will save yourself from a lengthy debugging cycle one day.

Line 27, 39: After you've run this script "as is," try removing the modifier flag on line 27 (you can "comment this out" by inserting # as the first character of the line).  When you run it again, notice what is missing from the output.  Since uppercase tag names are allowable in HTML documents, you might want to consider whether your script should also allow the use of uppercase.

Line 30-42: Test data!  Don't leave home without it.  In professional programming environments we require test data and we require automated testing.  If you make this a habit you will save yourself from a lot of unwanted run-time failures.  The quality of your work products will almost always correlate to the quality and completeness of your test data sets.

Line 47: Like most PHP functions, preg_match_all() returns a value.  You might want to check the man page to see what could be injected into $num by running this function.

Line 54: This function is the programmer's best friend.  When you get used to using it and seeing the output you will never write code without having it at your fingertips!

Line 60-63: Shows the way to use the foreach() iterator and address multidimensional arrays returned by preg_match_all().

You can see this little script in action here.  I encourage you to copy it, install it on your own server, and experiment with it to see exactly how it works.
http://iconoun.com/demo/temp_lawrence_dev.php

<?php // demo/temp_lawrence_dev.php

/**
 * SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28590226.html
 * REF http://www.experts-exchange.com/Programming/Languages/Regular_Expressions/Q_22417431.html
 */
error_reporting(E_ALL);

/**
 * A REGULAR EXPRESSION TO ISOLATE VALUES AND TEXTS FROM HTML OPTION TAGS
 *
 * REFERENCES:
 * http://php.net/manual/en/reference.pcre.pattern.syntax.php
 * http://php.net/manual/en/reference.pcre.pattern.modifiers.php
 * http://php.net/manual/en/function.preg-match-all.php
 * http://php.net/manual/en/function.preg-quote.php
 *
 */
$rgx
= '%'                            // REGEX DELIMITER
. preg_quote('<option value="')  // STRING LITERAL
. '(.*?)'                        // #1 CAPTURE GROUP OF ANYTHING OR NOTHING
. '">'                           // STRING LITERAL
. '(.*?)'                        // #2 CAPTURE GROUP OF ANYTHING OR NOTHING
. preg_quote('</option>')        // STRING LITERAL
. '%'                            // REGEX DELIMITER
. 'i'                            // MODIFIER - CASE-INSENSITIVE
;

/**
 * THE MOST IMPORTANT THING A PROGRAMMER CAN HAVE -- SOME TEST DATA
 * REF http://www.w3schools.com/tags/tag_select.asp
 */
$htm = <<<EOF
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <OPTION value="audi">Audi</option>
  <option value="bmw">BMW</option>
</select>
EOF;

/**
 * PERFORM THE MATCH AND SHOW THE WORK PRODUCT
 */
$num = preg_match_all($rgx, $htm, $mat);

echo '<pre>';
echo PHP_EOL . "FOUND $num MATCHES";
echo PHP_EOL . "USE 'VIEW SOURCE' TO SEE THE DATA";
echo PHP_EOL;

var_dump($mat);

/**
 * USE AN ITERATOR TO ACCESS THE MATCHED DATA
 * REF http://php.net/manual/en/control-structures.foreach.php
 */
foreach ($mat[1] as $key => $val)
{
    echo PHP_EOL . "OPTION VALUE ATTRIBUTE AT $key ('$val') HAS TEXT: " . $mat[2][$key];
}

Open in new window

And good luck with your PHP adventures, ~Ray
0
 

Author Comment

by:lawrence_dev
ID: 40532775
OK I have looked for options and don't really have a good grasp of this.  Once I see it in motion, I will understand it.  

I have up to 3 selects on each page.  I need to pull the options for each select by preg_match or preg_match_all.

Please advise how to do it...  Thx.

<form action="/A6148A4C" method="post">
                    <label for="618">Color</label>
					<span class="choice">
					<select id="opt618"  name="opt618"  class="isoption" style="max-width:250px;" >
					<option value="93C">Black</option>
					<option value="D4E">Fire Navy</option>
					<option value="98C">Heather Grey</option>
					</select></span>
					<label for="DF5">Length</label>
					<span class="choice">
					<select id="optDF5"  name="optDF5"  class="isoption" style="max-width:250px;" >
					<option value="78E">Regular</option>
					<option value="222">Tall</option>
					</select></span>
					<label for="8A1">Size</label>
					<span class="choice">
					<select id="opt8A1"  name="opt8A1"  class="isoption" style="max-width:250px;" >
					<option value="1F1">2XL</option>
                                       <option value="AA1">3XL</option>
					<option value="DC0">4XL</option>
                                         <option value="1D7">5XL</option>
					<option value="A25">Large</option>
                                       <option value="359">Medium</option>
					<option value="0B0">Small</option>
                                        <option value="680">XL</option>
					<option value="DFB">XS</option>
					</select></span>

Open in new window

0
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 
LVL 35

Expert Comment

by:Terry Woods
ID: 40533113
Something like:
preg_match_all('#<select.*?</select>#si', $buffer, $selects);
$selectnum=0;
foreach ($selects as $select) {
  $selectnum++;
  preg_match_all('#[^>]+(?=</option>)#si', $select, $options);
  print "Options for select $selectnum:<br>";
  print_r($options);
}

Open in new window


Note I'm not in a position to test this right now, but fingers crossed I can write some bug free code for once... let me know how you go and I'm happy to provide some explanation of what's happening.
0
 

Author Comment

by:lawrence_dev
ID: 40533857
OK, I am learning.  
I am getting an error.  

Warning: preg_match_all() expects parameter 2 to be string, array on this line:
preg_match_all ('#[^>]+(?=</option>)#si', $select, $options);

preg_match_all('#<select.*?</select>#si', $buffer, $selects);
$selectnum=0;
foreach ($selects as $select) {
  $selectnum++;
  preg_match_all ('#[^>]+(?=</option>)#si', $select, $options);  //error here
  print "Options for select $selectnum:<br>";
  print_r($options);
}

Open in new window


Thank you for your help!
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40536437
Ok, let's output the result of the first preg_match_all, so we know what data we're dealing with:
preg_match_all('#<select.*?</select>#si', $buffer, $selects);
print_r($selects); 
die();

Open in new window

0
 

Author Comment

by:lawrence_dev
ID: 40539272
This is the response from the above code.


Warning: preg_match_all() expects parameter 2 to be string, array given
Options for select 1:

Open in new window




Thanks for your assistance!
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40539777
Ok, so your variable $buffer is an array. Do you have multiple values you need to search through?

Ray's suggestion of reading up on programming in PHP is probably helpful if you're not sure how to manage your data in arrays.
0
 

Author Comment

by:lawrence_dev
ID: 40541243
Here are the correct results:

Array ( [0] => Array ( [0] =>dropdown [1] =>dropdown ) )

Array ( [0] => Array ( [0] =>Black [1] =>32 Regular ) )     (multiple results in each drop down)
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40542430
Sorry; I'm not clear on exactly what that data is. Is that the value of $buffer?
0
 

Author Comment

by:lawrence_dev
ID: 40542431
Yes.
0
 
LVL 35

Accepted Solution

by:
Terry Woods earned 2000 total points
ID: 40542614
The data structure of $buffer affects how you need to write the code. If it's as simple as taking the array in $buffer[0] and doing a foreach, then it would be something like this:
foreach($buffer[0] as $string) {
  preg_match_all('#<select.*?</select>#si', $string, $selects);
  $selectnum=0;
  foreach ($selects as $select) {
    $selectnum++;
    preg_match_all('#[^>]+(?=</option>)#si', $select, $options);
    print "Options for select $selectnum:<br>";
    print_r($options);
  }
}

Open in new window

0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question