preg_match/regex format needed - php

I have the below post fields submitted and I am trying to get the value of each of the numbers in the form field for the Quantity. Can someone help me with the regexp? I am trying to get each of the numbers in a variable.
FORMAT
Quantity_{Category}_{Product}_{Item}
POST FIELDS SUBMITTED
[submitted] => 1
[Quantity_12038_16061_24960] => 1
[Quantity_12037_16060_24959] => 2
[btnBuyNow] => Next Step
PHP CODE
foreach ($_POST as $key => $value) {
if (preg_match('/^Quantity_(\d+)$/', $key, $matches)) {
echo 'Key:' . $key . '<br>';
echo 'Matches:' . $matches . '<br>';
echo '<hr>';
}
}

Use preg_match() docs for this purpose, and that is a sample of how the code would look like:
$subject="Quantity_12038_16061_24960";
$pattern='/Quantity_(\d+)_(\d+)_(\d+)/';
preg_match($pattern, $subject, $matches);
echo $matches[0]; //12038 {Category}
echo $matches[1]; //16061 {Product}
echo $matches[2]; //24960 {Item}
you can see how this regex is performing here.

As the question is stated, regex is not needed:
foreach($_POST as $key => $val) {
if(strpos($key, 'Quantity') === 0) {
$results = explode('_', $key);
print_r($results);
}
}
To get rid of the Quantity string for whatever reason just unset($results[0]);.

Related

check a string contains any word from array

i have a set of predefined array contains strings and words.I am trying to check whether my string contains at least one word from that array.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
i tried many ways,but not correct solution
first method
$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";
second method
if (stripos(json_encode($array),$string) !== false) { echo "found";}
else{ echo "not found";}
I suppose you are looking for a match which is any of the words.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code|testy';
foreach ($array as $item ) {
if(preg_match("/\b{$string}\b/i", $item)) {
var_dump( $item );
}
}
You have to iterate over the array and test each one of the cases separately, first 'code', then 'testy', or whatever you want. If you json_encode, even if you trim both of strings to do this comparaison, the return will be not found.
But in the first string if you had like this
$array = array("PHP code testy Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
you will get surely a "found" as return.
if (stripos(trim(json_encode($array)),trim($string)) !== false) { echo "found";}
else{ echo "not found";}
You could use explode() to get an array from the strings and then go through each of them.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';
foreach(explode(' ', $string) as $key => $value) {
foreach($array as $arrKey => $arrVal) {
foreach(explode(' ', $arrVal) as $key => $str) {
if ($value == $str) {
echo $str . ' is in array';
}
}
}
}

How to check the array key matches specific string in php

$array = array(
"[ci_id]" => '144309',
"[NEW flag]" => 'No',
"[[*PRODUCT_IMAGE_ANCHOR1*]]" => ,
"[[*PRODUCT_IMAGE2*]]" => '154154154'
);
I need to get the elements which have pattern like '[['.
I have tried by using array_key_exists():-
if (array_key_exists('[*PRODUCT_IMAGE2*]', $array))
But i want to match only with '['
Can any one help me on this
Use preg_grep() with array_keys() like below:-
$matches = preg_grep ('/[.*?]/i', array_keys($array));
print_r($matches);
Output:- https://eval.in/817299
Or can do it using strpos() also:-
foreach($array as $key=>$val){
if(strpos($key,'[')!== false){
echo $key ."is matched with [*] pattern";
echo PHP_EOL;
}
}
Output:- https://eval.in/817297
The following code will give the true for the key with double [[ in if you know the element index value
$test = array("a"=>'a',"[a]"=>'a',"[[a]]"=>'a',"b"=>'b',"c"=>'c');
var_dump(array_key_exists("[[a]]", $test));
If you can checking the keys to determine if [[ even exist then the following code should work
$test = array("a"=>'a',"[a]"=>'a','[[a]]'=>'a',"b"=>'b',"c"=>'c');
$values = array();
foreach ($test as $key=>$value) {
if (stripos('[[', substr($key, 0, 2)) !== false) {
array_push($values, $value);
}
}

check if a word in string match with a key in array, then replace it

i want to find a keyword inside a string, im trying to make the script to find it and then replace it, but only that keyword (of course if others are found, replace them as well). but im lack of experience for this job and im trying to do it just for practice. this is my beginning code:
$var = array(
'{test1}' => 'something1',
'{test2}' => 'something2',
'{test3}' => 'something3'
);
$output = 'Please work it var {test1}!';
foreach($var as $element)
{
if(strstr($output, $element) !== false)
{
echo 'not found<br>';
}
else
{
echo 'found<br>';
}
}
for now im just checking if its found, but what i dont understand, why its repeating? it should just say "found" once and then say "not found", like this (found, not found, not found).
output:
found
found
found
This is a little confusing for me, as strstr is usually used to grab a portion of the string. I think a more appropriate approach would be using strpos. also you're not testing the key. don't even know why it's saying found. try
foreach($var as $key=>$val)
{
if(strpos($output, $key) !== false)
{
//the key is contained in the output.
}
else
{
//not found
}
}
if you let us know what you're trying to replace, I can see about helping with that. Also don't listen to everyone telling you to use == to compare against false. === or !== is the appropriate comparison as there are other things that == false(ie.. 0 ==false).
Realistically though, if you're trying to just replace the key of your array with the value, there is no need for a check.
foreach($var as $key=>$val)
$output = str_replace($key, $value, $output);
if the key is not found, nothing happens, if it is, it's replaced with its corresponding value. No check necessary.
First of all you have your if statement wrong. It is not finding it 3 times, that's why it is repeating (3 times for each item in your array):
if(strstr($output, $element) == false)
Remove the !. What you are saying is, if a match is found then echo "not found".
That is one problem, the second is that your code will not work. You are looking for the values of your array, rather than the keys. Try this:
$var = array(
'{test1}' => 'something1',
'{test2}' => 'something2',
'{test3}' => 'something3'
);
$output = 'Please work it var {test1}!';
foreach($var as $search => $replace)
{
if(strstr($output, $search) == false)
{
echo 'not found<br>';
}
else
{
echo 'found<br>';
}
}
The difference here is that you can access the array keys and values in the foreach buy using foreach (array_expression as $key => $value). I named the array keys $search since that is what you are looking for. Then you can access the array value using $replace to replace the string once found like so:
$var = array(
'{test1}' => 'something1',
'{test2}' => 'something2',
'{test3}' => 'something3'
);
$output = 'Please work it var {test1}!';
foreach($var as $search => $replace)
{
if(strstr($output, $search) == false)
{
echo 'not found<br>';
}
else
{
echo 'found - (' . str_replace($search, $replace, $output) . ')<br>';
}
}

PHP Turn a Numbered String List into Array

With PHP if you have a string which may or may not have spaces after the dot, such as:
"1. one 2.too 3. free 4. for 5.five "
What function can you use to create an array as follows:
array(1 => "one", 2 => "too", 3 => "free", 4 => "for", 5 => "five")
with the key being the list item number (e.g the array above has no 0)
I presume a regular expression is needed and perhaps use of preg_split or similar? I'm terrible at regular expressions so any help would be greatly appreciated.
What about:
$str = "1. one 2.too 3. free 4. for 5.five ";
$arr = preg_split('/\d+\./', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);
I got a quick hack and it seems to be working fine for me
$string = "1. one 2.too 3. free 4. for 5.five ";
$text_only = preg_replace("/[^A-Z,a-z]/",".",$string);
$num_only = preg_replace("/[^0-9]/",".",$string);
$explode_nums = explode('.',$num_only);
$explode_text = explode('.',$text_only);
foreach($explode_text as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$text_array[] = $value;
}
}
foreach($explode_nums as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$num_array[] = $value;
}
}
foreach($num_array as $key => $value)
{
$new_array[$value] = $text_array[$key];
}
print_r($new_array);
Test it out and let me know if works fine

Search for a part of an array and get the rest of it in PHP

I've got an array called $myarray with values like these:
myarray = array (
[0] => eat-breakfast
[1] => have-a-break
[2] => dance-tonight
[3] => sing-a-song
)
My goal is to search for a part of this array and get the rest of it. Here is an example:
If i submit eat, I would like to get breakfast.
If i submit have, I would like to get a-break.
I just try but I'm not sure at all how to do it...
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
It displays:
eat-breakfastArray ( )
But I want something like that:
breakfast
I think I'm totally wrong, but I don't have any idea how to proceed.
Thanks.
use
stripos($word, $myarray)
<?php
$myarray = array (
'eat-breakfast',
'have-a-break',
'dance-tonight',
'sing-a-song'
) ;
function search($myarray, $word){
foreach($myarray as $index => $value){
if (stripos($value, $word) !== false){
echo str_replace(array($word,'-'), "", $value);
}
}
}
search($myarray, 'dance');
echo "<br />";
search($myarray, 'have-a');
echo "<br />";
search($myarray, 'sing-a');
demo
I think the word you seek is at the beginning. Try this
function f($myarray, $word)
{
$len = strlen($word);
foreach($myarray as $item)
{
if(substr($item, 0, $len) == $word)
return substr($item, $len+1);
}
return false;
}
You're feeding the wrong information into preg_match, although I'd recommend using array_search().. Check out my updated snippet:
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
To get rid of that last bit, just perform a str_replace operation to replace the word with ""
This will both search the array (with a native function) and return the remainder of the string.
function returnOther($search, $array) {
$found_key = array_search($search, $array);
$new_string = str_replace($search . "-", "", $array[$found_key]);
return $new_string;
}

Categories