Get selected option value from html select with regular expression - php

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

Related

Finding the value of an option with specific string

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

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.

Make the value of a select box the same as the name of the option without copy paste

my question is how can I replace all the values with the option name without copy paste.
The new list will be happen once, so that it can help me to win hours of copy-paste.
It's been a puzzle to me. Thanks for your solutions and ideas.
<option value="61">Talbot</option>
<option value="3830">Tata</option>
<option value="248">Toyota</option>
<option value="63">Trabant</option>
<option value="64">Triumph</option>
<option value="651">Uaz</option>
This is an example of what I want
<option value="Talbot">Talbot</option>
If you want to do this with PHP you should use preg_replace() function
It will look something like this:
<?php
$ptn = "/<option value=\"(.*)\">(.*)<\/option>/";
$str = '<option value="61">Talbot</option>';
$rpltxt = '<option value="$2">$1</option>';
echo preg_replace($ptn, $rpltxt, $str);
?>
output will be:
<option value="Talbot">61</option>
because most people do interesting things with whitespace, case, and quotes, there are few guarantees.
a proper search regex would look like
"/<[oO][pP][tT][iI][oO][nN]\s+[vV][aA][lL][uU][eE]\s*=\s*['\"]?(.*)['\"]?\s*>(.*)</[oO][pP][tT][iI][oO][nN]>/"
replace with "<option value=\"$2\">$2</option>"
the first set of perens are not required (but the .* is).

Categories