Finding the value of an option with specific string - php

Consider this snippet from select form:
<select name="cat_id"">
<option value="33">Apple</option>
<option value="44">Banana</option>
<option value="48">Carrot</option>
<option value="50">Dew</option>
<option value="77">Eggplant</option>
<option value="84">Fern</option>
<option value="92">Grass</option>
</select>
Is there a way, using SIMPLE DOM, I can extract the value="x" for specific string.
Example, I want to get the value of Dew, hence, I must be able to get 50
Tried searching and playing, but cannot find exact answer:
Parsing drop down menu with php simple dom <-- But values doesn't start from 0 nor increments uniformly
php , simple_html_dom.php, get selected option <-- I do not even have selected entry in the select form
I need to get the value for specific string so that I can use it to send form using cURL.
Hope, somebody can help. Thanks in advance and more power.

The following code will parse all option nodes and when the searched text is matched, it will display the corresponding value and ends:
$input = <<<_DATA_
<select name="cat_id">
<option value="33">Apple</option>
<option value="44">Banana</option>
<option value="48">Carrot</option>
<option value="50">Dew</option>
<option value="77">Eggplant</option>
<option value="84">Fern</option>
<option value="92">Grass</option>
</select>
_DATA_;
// Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($input);
// searched text
$searchText = 'dew';
// Create a regex pattern (match $searchText followed OR preceded by any number of spaces/tabs/newLines ...)
// i flag stands for case insensitive match
$pattern = '/\s*'.$searchText.'\s*/i';
foreach( $html->find('select[name="cat_id"] option') as $option ){
echo $string = $option->plaintext;
// Check if the current node contains the searched text
if( preg_match($pattern, $string) ){
$value = $option->value;
echo ' => ' . $value;
// Exit the loop when done
break;
}
echo '<br>';
}
OUTPUT
Apple
Banana
Carrot
Dew => 50

Related

Get selected option value from html select with regular expression

See the below list of options, i am trying to get value of option which is selected.
<select>
<option {class='test'} value="volvo" selected='selected'>Volvo</option>
<option {class='test'} value="saab">Saab</option>
<option {class='test'} value="mercedes">Mercedes</option>
<option {class='test'}value="audi">Audi</option>
</select>
in the above example i need to get volvo as the matched string. there may or may not have any class parameter.
That's if option string is
<option {class='test'} value="volvo" selected='selected'>Volvo</option>
or
<option value="volvo" selected='selected'>Volvo</option>
Regular expression should return volvo.
That's a regular expression suitable for all cases.
I tried with
preg_match_all('/<option\sclass="[^"]*"\svalue="([^"]*)">([^>]*)<\/option>/', $string, $matches);`
But that didn't return value of the selected item. Please help.
Try this:
$re = '/^.*\<option.*value=(?:\'|")([a-z]*)(?:\'|").*(?=selected=(?:\'|")selected(?:\'|")).*$/m';
$str = '<select>\n <option {class=\'test\'} value="volvo" selected=\'selected\'>Volvo</option>\n <option {class=\'test\'} value="saab">Saab</option>\n <option {class=\'test\'} value="mercedes">Mercedes</option>\n <option {class=\'test\'} value="audi">Audi</option>\n</select> ';
preg_match_all($re, $str, $matches);
echo "<pre>";
var_dump($matches);
I changed the logic of the expression from this:
/<option\sclass="[^"]*"\svalue="([^"]*)">([^>]*)<\/option>/
to this:
/^.*\<option.*value=(?:\'|")([a-z]*)(?:\'|").*(?=selected=(?:\'|")selected(?:\'|")).*$/m
and worked fine. See the regex101 example
However I really don't recommend regex for parsing html.
I think you should take a look into other ways to accomplish your task, eg. how-do-you-parse-and-process-html-xml-in-php

Replace dynamically value of options while passing the output of a php function

I have a string ($options) stored in a PHP var which contains of a series of <option> elements which look like the following:
<option class="level-0" value="898">Text 1</option>
<option class="level-1" value="33"> Text 2</option>
<option class="level-2" value="543"> Text 3</option>
<option class="level-1" value="547"> Text 4</option>
<option class="level-0" value="3328">Text 5</option>
I want to replace the content of each value with the result of a function which takes the former value to generate a URL. The URL string (which is variable) should become the new value for each corresponding <option>. I want to retain the rest exactly as it is.
I'm not sure if this is achievable with preg_replace, yet I would know how to do it if each option was an array with keys, but it's a variable string... How would you do it?
$lines = explode(PHP_EOL, $options);
$new_options = array();
foreach ($lines as $option_line) {
//do the preg replace for each line (quick and dirty regexp)
$replaced_string_value = preg_replace('/>(\w+)<\//i', '>replacement<\\', $option_line);
//add it to the new array
$new_options[] = $replaced_string_value;
}
$options = implode(PHP_EOL, $new_options);

simple_html_dom class, What actually plaintext function returns?

I think i don't get it. I tried to parse some html page :
<select name="sel">
<option value="val0">-please select me-</option>
<option value="val1">some selection</option>
</select>
Im using the Simple_html_dom class :
foreach($html->find('select') as $s) {
if ($html->find('option',1) != false) {
$tempoption = $html->find('option',1)->plaintext;
echo $tempoption; //shows 'some selection'
}
}
but, then if i simply use this line :
$value='';
if ( $tempoption == 'some selection')
$value='79';
echo $value; //doesn't shows anything (empty variable?)
//or this one :
if ( strcmp($tempoption, 'some selection'))
$value='79';
echo $value; //Nope.
I tried out the code just as you had it there and $value DID end up with 79. But I think that you must have more to your HTML than that tiny snippet. The thing in your code that stood out most to me was the fact that you are wrapping the conditionals in a loop that goes through all the selects of the HTML, but you are not making use of the individual select elements that you get from the loop, so the foreach loop seems pointless..
Have a look at this:
foreach($html->find('select option') as $o)
{
$o_label = $o->plaintext;
if($o_label=='some selection') echo 'PERFECT MATCH: '.$o_label."\n";
else if(stripos($o_label, 'some selection')!==false) echo 'LOOSE MATCH: '.$o_label."\n";
else echo 'DOES NOT MATCH: '.$o_label."\n";
}
When given HTML:
<select name="sel">
<option value="val0">-please select me-</option>
<option value="val1">1 some selection</option>
<option value="val1">This does not match</option>
<option value="val1">some selection</option>
<option value="val1">Another non-matching label</option>
<option value="val1">some selection 3</option>
<option value="val1">One more that does not match</option>
<option value="val1">4 SoME sElEcTIon 4</option>
</select>
The output will be:
DOES NOT MATCH: -please select me-
LOOSE MATCH: 1 some selection
DOES NOT MATCH: This does not match
PERFECT MATCH: some selection
DOES NOT MATCH: Another non-matching label
LOOSE MATCH: some selection 3
DOES NOT MATCH: One more that does not match
LOOSE MATCH: 4 SoME sElEcTIon 4

Get Text From <option> Tag Using PHP

I want to get text inside the <option> tags as well as its value.
Example
<select name="make">
<option value="5"> Text </option>
</select>
I used $_POST['make']; and I get the value 5 but I want to get both value and the text.
How can I do it using PHP?
In order to get both the label and the value using just PHP, you need to have both arguments as part of the value.
For example:
<select name="make">
<option value="Text:5"> Text </option>
</select>
PHP Code
<?php
$parts = $_POST['make'];
$arr = explode(':', $parts);
print_r($arr);
Output:
Array(
[0] => 'Text',
[1] => 5
)
This is one way to do it.
What about this? I think it's the best solution because you have separated fields to each data. Only one hidden field which is updated at each change and avoids hardcoding mappings.
This inside HTML:
<select name='make' onchange="setTextField(this)">
<option value = '' selected> None </option>
<option value = '5'> Text 5 </option>
<option value = '7'> Text 7 </option>
<option value = '9'> Text 9 </option>
</select>
<input id="make_text" type = "hidden" name = "make_text" value = "" />
<script type="text/javascript">
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
This inside PHP:
<?php
$value = $_POST["make"];
$text = $_POST["make_text"];
?>
set the value of text to the value of the option tag, be it through static HTML markup or even if it's being generated by a server side script. You will only get the value attribute through POST
Another option however, on the server side, is to map the value ("5"), to an associative array, i.e.
<?php
$valueTextMap = array("5" => "Text");
$value = $_POST['make']; //equals 5
$text = $valueTextMap[$value]; //equals "Text"
?>
You'll need to include that Text in the value to begin with (e.g.: <option value="5_Text"> Text </option> and then parse, or...
You could use javascript on the page to submit the text as another parm in the POST action.
You can use simple dom
<?php
include('/mnt/sdb1/addons/simplehtmldom/simple_html_dom.php');
$html = file_get_html('tari.html');
$opt = array();
foreach($html->find('option') as $a) {
$opt[] = $a->value;
}
print_r($opt);
?>
I have always used a very elegant solution, similar to the ones already presented, which does not require a lot of additional code.
HTML
<select name="make">
<option value="1:First Option">First Option Text</option>
<option value="2:Second Option">Second Option Text</option>
<option value="3:Third Option Text">Third Option Text</option>
</select>
PHP
$value = split(':', $make)[0];
$text = split(':', $make)[1];
Benefits of this method
Yes, there are definitely similarities to serialworm's answer, yet we minimize the code in our PHP block by inconspicuously converting to an array and picking the element required right away.
In my case, I use this exact short-hand code in a contact form where this one-liner (to get the selected department name) is critical to keeping the code looking clean.

Creating a select dropdown from a .txt?

I've a select menu hardcoded in a wordpress (php) theme, but the manager requires to edit those frequently. Is it possible to populate the select dropdown options from a text file import? So he just has to edit the text file and the menu options would change.
The current menu looks like this:
<select name="location" id="sort-location" class="sort-dropdown">
<option value="" selected="selected">LOCATION:</option>
<option value="" disabled="">--------------</option>
<option value="hongkong">Hong Kong</option>
<option value="taiwan">Taiwan</option>
<option value="mainland_china">Mainland China</option>
<option value="" disabled="">--------------</option>
<option value="">SHOW ALL</option>
</select>
Sure -- make yourself a small loop that runs through the lines in the format you choose.
<?php
$select = file_get_contents('select.txt');
$lines = explode("\n", $select);
foreach ($lines as $line) {
// let's say our format is like this:
// value|name|selected|disabled
// or:
// -
// for separator
if ($line == '-') {
echo '<option disabled="disabled">----------</option>';
} else {
list($value, $name, $selected, $disabled) = explode("|",$line);
echo '<option value="'.$value.'"',
$selected?' selected="selected"':'',
$disabled?' disabled="disabled"':'',
'>'.$name.'</option>';
}
}
?>
Sure, just fetch the text file into an array using file() and create the select out of it. A very simple implementation: menu.txt:
hongkong Hong Kong
taiwan Taiwan
mainland_china Mainland China
Note the tabs between value and label.
Then in PHP:
$menu_items = file("menu.txt");
foreach ($menu_items as $menu_item)
{
// Explode
$menu_item_exploded = explode("\t", $menu_item);
$option_value = htmlspecialchars(trim($menu_item_exploded[0]));
$option_label = htmlspecialchars(trim($menu_item_exploded[1]));
echo "<option value='$option_value'>$option_label</option>";
}
As far as I can see, you have the following left to solve:
How to pre-set a predefined value (You need to echo selected in the right item)
How to deal with the user editing out a value from the text file that was pre-set in your select.
Error handling if the file is not existent or not accessible
Error handling if the user screws up the line breaks, or something similar - maybe count the lines, and/or detect whether there are tabs inside the file

Categories