I have a preg_match_all that is generating an array of urls from a string. The array resembles:
$url[0] = "http://www.siteone.com";
$url[1] = "http://www.sitetwo.com";
$url[2] = "http://www.sitethree.com/example1";
$url[3] = "http://www.sitefour.com";
$url[4] = "http://www.sitethree.com/example2";
$url[5] = "http://www.sitefive";
$url[6] = "http://www.sitesix";
$url[7] = "http://www.siteseven";
$url[8] = "http://www.sitethree.com/example3";
However, I need to be able to search through the #url array to change the value when it contains "http://www.sitethree.com" and set this particular value in the array to "no value". So that once this process was applied,, it would the array would look like this:
$url[0] = "http://www.siteone.com";
$url[1] = "http://www.sitetwo.com";
$url[2] = "no value";
$url[3] = "http://www.sitefour.com";
$url[4] = "no value";
$url[5] = "http://www.sitefive";
$url[6] = "http://www.sitesix";
$url[7] = "http://www.siteseven";
$url[8] = "no value";
I have tried numerous variations of preg_match_all and if statements within loops but just couldn't get it. Any help would be greatly appreciated.
$url = array_map(function($v) {
return strpos($v, 'http://www.sitethree.com') === false ? $v : 'no value';
}, $url);
foreach ($url as &$value) {
if (strpos($value, 'http://www.sitethree.com') === 0) {
$value = 'no value';
}
}
foreach($url as $id => $link){
if(strstr($link, 'sitethree.com')){
$url[$id] = 'no value';
}
}
print_r($url);
A simple way of doing it is this:
foreach($url as $key => $value)
{
if(stristr($value, "http://www.sitethree.com"))
{
$url[$key] = "no value";
}
}
Related
My goal is:
If a value in those arrays match with an extention of a file, then I can builds a nice URL encoded string which I can append to a url using the http_build_query() function. If no match is found, it return nothing.
I have tried it every possible way and it doesn't work, as the code below. can you check on which part is wrong ?.
$name = 'myfile.mp4';
$list = array(
'video' => array('3gp', 'mkv', 'mp4'),
'photo' => array('jpg', 'png', 'tiff')
);
// File Ext Check
$ext = (strpos($name, '.') !== false) ? strtolower(substr(strrchr($name, '.'), 1)) : '';
$type = null;
$find = $ext;
array_walk($list, function ($k, $v) use ($find, &$type)
{
if (in_array($find, $k))
{
$type = $v;
$data = array();
switch ($type)
{
case 'video':
$data['title'] = 'video';
$data['description'] = 'my video';
break;
case 'photo':
$data['title'] = 'photo';
$data['description'] = 'my photo';
break;
}
}
else {
echo "not both!.";
exit;
{
});
if ($type == 'video') {
$link = 'https://www.video.com' . http_build_query($data);
}
else
if ($type == 'photo') {
$link = 'https://www.photo.com' . http_build_query($data);
}
echo $link;
Thank you...
You $data is set in the array_walk() scope, but out of the array_walk() scope is not defined. So in the http_build_query($data), here $data has not defined.
You may referende the $data in the use(), then after the array_walk(), you can use its value. In your code you use in_array() to check the file type in a list, for performance I recomend you to see this post.
i have a variable array that gets all what my function has retrieved.
$array = $funcs->searchCompany($bizName);
and then i used foreach to check if the value is null for varchar and 0 for int and then i replace its value to "Not Provided" so that everytime it is being called it will say "Not Provided"
foreach ($array as $var) {
if($var == " " || $var == 0) {
$var = "Not Provided";
}
}
$name = $var['name'];
$url = $var['url'];
$tagline = $var['tagline'];
$descrip = $var['descrip'];
$bemail = $var['bemail'];
$address = $var['address'];
$city = $var['city'];
but it seems wrong because it destroys the output instead.
You can use & here to pass the value of array to change inside foreach without actually worrying about which is the current array key, which is also sometimes called as passing a variable's value by reference.
Using foreach
foreach ($array as &$value) // note the &
{
if(empty($value)) $value = 'Not Provided';
// other values remain untouched
}
Using array_map()
$array = array_map(function($value){
if(empty($value))
return 'Not Provided';
return $value;
}, $array);
But i will suggest to go with foreach.
update your function so something like
foreach ($array as &$var) {
if($var == " " || $var == 0) {
$var = "Not Provided";
}
}
$name = $array['name'];
$url = $array['url'];
$tagline = $array['tagline'];
$descrip = $array['descrip'];
$bemail = $array['bemail'];
$address = $array['address'];
$city = $array['city'];
I would try something like this . I can not write comments so I am writing it as an answer.
What I understand from your code is your array has key value relation. That is most probably why it is not working with your single dimensional array iteration.
try this instead.
foreach ($array as $var => $value) {
if($value == " " || $value == 0 || $value == null) {
$array[$var] = "Not Provided";
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
Give it a try.
I have this code:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
if(in_array("backup", $arr)){
echo "Da";
} else { echo "Nu";
}
But is not working because,in_array instruction check the array for the complete string "backup" , which doesnt exist.I need to check for a part of the string,for example,to return true because backup is a part of the "Hello_backup" and "Beautiful_backup" strings
EDIT: I take the advice and i have used stripos like this:
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$word='backup';
if(stripos($arr,$word) !== false){
echo "Da";
} else { echo "Nu";}
but now i get an error: "stripos() expects parameter 1 to be string, array given in if(stripos($arr,$word) !== false){"
Use implode to basically concatenate the array values as a string, then use strpos to check for a string within a string.
The first argument you pass to implode is used to separate each value in the array.
$array = array("Hello_backup","World!","Beautiful_backup","Day!");
$r = implode(" ", $array);
if (strpos($r, "backup") !== false) {
echo "found";
}
In this case you need to use stripos(). Example:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$needle = 'backup';
function check($haystack, $needle) {
foreach($haystack as $word) {
if(stripos($word, $needle) !== false) {
return 'Da!'; // if found
}
}
return 'Nu'; // if not found
}
var_dump(check($arr, $needle));
Without a function:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$found = false;
foreach($arr as $word) {
if(stripos($word, 'backup') !== false) {
$found = true;
break;
}
}
if($found) {
echo 'Da!';
} else {
echo 'Nu';
}
Try with strpos()
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $v){
echo (strpos($v,"backup")!== false ? "Da" : "Nu");
}
output :- DaNuDaNu
Here is the one line solution for you.
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$returned_a = array_map(function($u){ if(stripos($u,'backup') !== false) return "Da"; else return "Nu";}, $arr);
You can use $returned_a with array as your answer..
Array ( [0] => Da [1] => Nu [2] => Da [3] => Nu )
Use this method. It is little bit simple to use.
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
print_r($matches);
Look this working example
According to your question
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
$matches = trim($matches);
if($matches != '')
{echo "Da";
}else { echo "Nu";}
<?php
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $arr1) {
if (strpos ($arr1,"backup")) {
echo "Da";
} else {
echo "Nu";
}
}
?>
I am stuck. What I would like to do: In the $description string I would like to check if any of the values in the different arrays can be found. If any of the values match, I need to know which one per array. I am thinking that I need to do a function for each $a, $b and $c, but how, I don't know
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$a = array('1:100','1:250','1:10','2');
$a = getExtractedValue($a,$description);
$b = array('one','five','12');
$b = getExtractedValue($b,$description);
$c = array('6000','8000','500');
$c = getExtractedValue($c,$description);
}
}
}
function getExtractedValue($a,$description){
?
}
I would be very very greatful if anyone could help me with this.
many thanks Linda
It would be better to create each array just once and not in every iteration of the while loop.
Also using the same variable names in the loop is not recommended.
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
$a = array('1:100','1:250','1:10','2');
$b = array('one','five','12');
$c = array('6000','8000','500');
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$aMatch = getExtractedValue($a,$description);
$bMatch = getExtractedValue($b,$description);
$cMatch = getExtractedValue($c,$description);
}
}
}
Use strpos to find if the string exists (or stripos for case insensitive searches). See http://php.net/strpos. If the string exists it will return the matching value in the array:
function getExtractedValue($a,$description) {
foreach($a as $value) {
if (strpos($description, $value) !== false) {
return $value;
}
}
return false;
}
there s a php function for that which return a boolean.
or if you wanna check if one of the element in arrays is present in description, maybe you 'll need to iterate on them
foreach($array as element){
if(preg_match("#".$element."#", $description){
echo "found";
}
}
If your question is correctly phrased and indeed you are searching a string, you should try something like this:
function getExtractedValue($a, $description) {
$results = array();
foreach($a as $array_item) {
if (strpos($array_item, $description) !== FALSE) {
$results[] = $array_item;
}
}
return $results;
}
The function will return an array of the matched phrases from the string.
Try This..
if ( in_array ( $str , $array ) ) {
echo 'It exists'; } else {
echo 'Does not exist'; }
I've got a multidimensional associative array which includes an elements like
$data["status"]
$data["response"]["url"]
$data["entry"]["0"]["text"]
I've got a strings like:
$string = 'data["status"]';
$string = 'data["response"]["url"]';
$string = 'data["entry"]["0"]["text"]';
How can I convert the strings into a variable to access the proper array element? This method will need to work across any array at any of the dimensions.
PHP's variable variables will help you out here. You can use them by prefixing the variable with another dollar sign:
$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"
Quick and dirty:
echo eval('return $'. $string . ';');
Of course the input string would need to be be sanitized first.
If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe.
It does, however, make assumptions about the string format:
<?php
$data['response'] = array(
'url' => 'http://www.testing.com'
);
function extract_data($string) {
global $data;
$found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
if (!$found_matches) {
return null;
}
$current_data = $data;
foreach ($matches[1] as $name) {
if (key_exists($name, $current_data)) {
$current_data = $current_data[$name];
} else {
return null;
}
}
return $current_data;
}
echo extract_data('data["response"]["url"]');
?>
This can be done in a much simpler way. All you have to do is think about what function PHP provides that creates variables.
$string = 'myvariable';
extract(array($string => $string));
echo $myvariable;
done!
You can also use curly braces (complex variable notation) to do some tricks:
$h = 'Happy';
$n = 'New';
$y = 'Year';
$wish = ${$h.$n.$y};
echo $wish;
Found this on the Variable variables page:
function VariableArray($data, $string) {
preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER);
$return = $arr;
foreach($arr_matches[1] as $dimension) { $return = $return[$dimension]; }
return $return;
}
I was struggling with that as well,
I had this :
$user = array('a'=>'alber', 'b'=>'brad'...);
$array_name = 'user';
and I was wondering how to get into albert.
at first I tried
$value_for_a = $$array_name['a']; // this dosen't work
then
eval('return $'.$array_name['a'].';'); // this dosen't work, maybe the hoster block eval which is very common
then finally I tried the stupid thing:
$array_temp=$$array_name;
$value_for_a = $array_temp['a'];
and this just worked Perfect!
wisdom, do it simple do it stupid.
I hope this answers your question
You would access them like:
print $$string;
You can pass by reference with the operator &. So in your example you'll have something like this
$string = &$data["status"];
$string = &$data["response"]["url"];
$string = &$data["entry"]["0"]["text"];
Otherwise you need to do something like this:
$titular = array();
for ($r = 1; $r < $rooms + 1; $r ++)
{
$title = "titular_title_$r";
$firstName = "titular_firstName_$r";
$lastName = "titular_lastName_$r";
$phone = "titular_phone_$r";
$email = "titular_email_$r";
$bedType = "bedType_$r";
$smoker = "smoker_$r";
$titular[] = array(
"title" => $$title,
"first_name" => $$firstName,
"last_name" => $$lastName,
"phone" => $$phone,
"email" => $$email,
"bedType" => $$bedType,
"smoker" => $$smoker
);
}
There are native PHP function for this:
use http://php.net/manual/ru/function.parse-str.php (parse_str()).
don't forget to clean up the string from '"' before parsing.
Perhaps this option is also suitable:
$data["entry"]["0"]["text"];
$string = 'data["entry"]["0"]["text"]';
function getIn($arr, $params)
{
if(!is_array($arr)) {
return null;
}
if (array_key_exists($params[0], $arr) && count($params) > 1) {
$bf = $params[0];
array_shift($params);
return getIn($arr[$bf], $params);
} elseif (array_key_exists($params[0], $arr) && count($params) == 1) {
return $arr[$params[0]];
} else {
return null;
}
}
preg_match_all('/(?:(\w{1,}|\d))/', $string, $arr_matches, PREG_PATTERN_ORDER);
array_shift($arr_matches[0]);
print_r(getIn($data, $arr_matches[0]));
P.s. it's work for me.