PHP Extracting Operators and the values from String - php

in my code i need to get both operator and the values to do my calculation. my code is,
$demension = "3.5x2.3=>4.8x8.9"
public function searchItems($dimension)
{
$out= preg_split('/[x-]/', $dimension);
$i=0;
foreach ($out as $key) {
preg_match('/(!=|=|<=|<|>=|>)/',$key,$matches);
if(!empty($matches))
{
$result[$i]=$matches;
}else
{
$result[$i]=$key;
}
$i++;
}
return $result;
}
I need to get 3.5,2.3,=>,4.8,8.9 separately
can any one show me the right path.

Here it is. Using a regexp to get values and operators.
function getParts($string)
{
$regexp = "/(\d+?\.\d+?)|([<>=]+)/";
$parts = [];
if (preg_match_all($regexp, $string, $matches)) {
$parts = $matches[0];
}
return $parts;
}
$dimension = "3.5x2.3=>4.8x8.9"
print_r(getParts($dimension));

Related

How to get array from tagIds=3&tagIds=8

In PHP if a URL looks like this:
?tagIds[]=3&tagIds[]=8
PHP engine automatically transforms this into tagIds array. However, if a URL is missing square brackets:
?tagIds=3&tagIds=8
Automatic transformation into an array doesn't happen. How can I achieve the same manually in native PHP and in Kohana framework?
UPDATE:
It seems that I've found the answer. Can you please take a look at it's potential pitfalls? See my answer below.
It seems that I've found a solution here:
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$query = proper_parse_str($_SERVER['QUERY_STRING']);
Try this:
$str = "tagIds[]=3&tagIds[][]=8&tagIds=33";
function ext_parse_str( $str ) {
$vs = explode("&", $str);
$output = array();
foreach ($vs as $v) {
parse_str($v, $o);
if (is_array($o) && count($o)==1) {
$key = key($o);
$value = $o[$key];
var_dump($value);
if ($value) {
if (!is_array($value)) {
$output[$key][] = $value;
} else {
if (!isset($output[$key])) {
$output[$key] = $value;
} else {
$output[$key] = array_merge_recursive( $output[$key], $value );
}
}
}
}
}
return $output;
}
$query = ext_parse_str($str);
var_dump($query);

PHP check if a variable is LIKE an item in an array using in_array

I am creating this array with the below code:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
}
and i want to check if any item inside the array is LIKE a variable. I have this so far:
if(in_array($data[6], $ignored)) {
but I'm not sure what to do with the LIKE
in_array() doesn't provide this type of comparison. You can make your own function as follows:
<?php
function similar_in_array( $sNeedle , $aHaystack )
{
foreach ($aHaystack as $sKey)
{
if( stripos( strtolower($sKey) , strtolower($sNeedle) ) !== false )
{
return true;
}
}
return false;
}
?>
You can use this function as:
if(similar_in_array($data[6], $ignored)) {
echo "Found"; // ^-search ^--array of items
}else{
echo "Not found";
}
Function references:
stripos()
strtolower()
in_array()
Well, like is actually from SQL world.
You can use something like this:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
if ( preg_match('/^[a-z]+$/i', $ignored2) ) {
//do what you want...
}
}
UPDATE: Well, I found this answer, may be it's what you need:
Php Search_Array using Wildcard
Here is a way to do it that can be customized fairly easily, using a lambda function:
$words = array('one','two','three','four');
$otherwords = array('three','four','five','six');
while ($word = array_shift($otherwords)) {
print_r(array_filter($words, like_word($word)));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}
http://codepad.org/yAyvPTIq
To add different checks, simply add more conditions to the return. To do it in a single function call:
while ($word = array_shift($otherwords)) {
print_r(find_like_word($word, $words));
}
function find_like_word($word, $words) {
return array_filter($words, like_word($word));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}

Data Not Being Parsed Correctly

I have a simple data format that goes as follows:
stuff/stuff/stuff
An example would be:
data/test/hello/hello2
In order to retrieve a certain piece of data, one would use my parser, which tries to do the following:
In data/test/hello/hello2
You want to retrieve the data under data/test (which is hello). My parser's code is below:
function getData($data, $pattern)
{
$info = false;
$dataLineArray = explode("\n", $data);
foreach($dataLineArray as &$line)
{
if (strpos($line,$pattern) !== false) {
$lineArray = explode("/", $line);
$patternArray = explode("/", $pattern);
$iteration = 0;
foreach($lineArray as &$lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
else
{
$info = $lineData;
}
}
}
}
return $info;
}
However, it always seems to return the last item, which in this case is hello2:
echo getData("data/test/hello/hello2", "data/test");
Gives Me;
hello2
What am I doing wrong?
If you want the first element after the pattern, put break in the loop:
foreach($lineArray as $lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
elseif ($iteration == count($patternArray))
{
$info = $lineData;
break;
}
}
I also check $iteration == count($patternArray) so that it won't return intermediate elements, e.g.
/data/foo/test/hello/hello2
will return hello rather than foo.
P.S. There doesn't seem to be any reason to use references instead of ordinary variables in your loops, since you never assign to the reference variables.

Find the longest array value from given search ID

I have two arrays, one with a large set of URL paths and another with search IDs. Each of the URL paths has one unique ID in common. By the search ID we need to find the longest URL with the unique ID. Here is my code, I will explain a bit more later.
<?php
function searchstring($search, $array) {
foreach($array as $key => $value) {
if (stristr($value, $search)) {
echo $value;
}
}
return false;
}
$array = array(
"D:\winwamp\www\info\961507\Good_Luck_Charlie",
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1",
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1\episode_3",
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1\episode_3\The_Curious_Case_of_Mr._Dabney",
"D:\winwamp\www\info\961506\Good_Luck_Charl",
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1",
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1\episode_1",
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1\episode_1\Study_Date");
$searchValues = array("961507","961506");
foreach($searchValues as $searchValue) {
$result = searchstring($searchValue, $array);
}
?>
This gives the value of all matched IDs. Now if you see my array there are four sets of URL paths. What I want is that if I search with "961507" it should give:
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1\episode_3\The_Curious_Case_of_Mr._Dabney"
If i search with "961506", it should give:
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1\episode_1\Study_Date"
Now what I am getting are all the arrays that matched with my searched ID. Can you please help me to find out how can I accomplish this? Because I have more than 98000 URLs to sort out.
Change the function as
function searchstring($search, $array) {
$length = 0;
$result = "";
foreach($array as $key => $value) {
if (stristr($value, $search)) {
if($length < strlen($value)) {
$length = strlen($value);
$result = $value;
}
}
}
return $result;
}
To print value use:
foreach($searchValues as $searchValue) {
$result = searchstring($searchValue, $array);
echo $result;
}
Or
$result = array();
foreach($searchValues as $searchValue) {
$result[] = searchstring($searchValue, $array);
}
print_r($result);

Convert string to array value in PHP

If I had an array such as:
testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));
How would I go about converting a string such as testarray[bar][0] to find the value its describing?
Well, you can do something like this (Not the prettiest, but far safer than eval)...:
$string = "testarray[bar][0]";
$variableBlock = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$regex = '/^('.$variableBlock.')((\[\w+\])*)$/';
if (preg_match($regex, $string, $match)) {
$variableName = $match[1]; // "testarray"
if (!isset($$variableName)) {
//Error, the variable does not exist
return null;
} else {
$array = $$variableName;
if (preg_match_all('/\[(\w+)\]/', $match[2], $matches)) {
foreach ($matches[1] as $match) {
if (!is_array($array)) {
$array = null;
break;
}
$array = isset($array[$match]) ? $array[$match] : null;
}
}
return $array;
}
} else {
//error, not in correct format
}
You could use PHP's eval function.
http://php.net/manual/en/function.eval.php
However, make absolutely sure the input is sanitized!
Cheers

Categories