[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 101
  • Last Modified:

Need assistance with For Each loop

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
lawrence_dev
Asked:
lawrence_dev
  • 6
  • 5
1 Solution
 
Terry WoodsIT GuruCommented:
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
 
Ray PaseurCommented:
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
 
lawrence_devAuthor Commented:
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
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
Terry WoodsIT GuruCommented:
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
 
lawrence_devAuthor Commented:
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
 
Terry WoodsIT GuruCommented:
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
 
lawrence_devAuthor Commented:
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
 
Terry WoodsIT GuruCommented:
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
 
lawrence_devAuthor Commented:
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
 
Terry WoodsIT GuruCommented:
Sorry; I'm not clear on exactly what that data is. Is that the value of $buffer?
0
 
lawrence_devAuthor Commented:
Yes.
0
 
Terry WoodsIT GuruCommented:
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now