I have the following text string: "Gardening,Landscaping,Football,3D Modelling"
I need PHP to pick out the string before the phrase, "Football".
So, no matter the size of the array, the code will always scan for the phrase 'Football' and retrieve the text immediately before it.
Here is my (lame) attempt so far:
$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'
Any help with this would be greatly appreciated.
Many thanks
$terms = explode(',', $array);
$index = array_search('Football', $terms);
$indexBefore = $index - 1;
if (!isset($terms[$indexBefore])) {
trigger_error('No element BEFORE');
} else {
echo $terms[$indexBefore];
}
//PHP 5.4
echo explode(',Football', $array)[0]
//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
$array = array("Swimming","Astronomy","Gardening","Rugby","Landscaping","Football","3D" "Modelling");
$find = "Football";
$string = getFromOffset($find, $array);
echo $string; // $string would = 'Landscaping'
function getFromOffset($find, $array, $offset = -1)
{
$id = array_search($find, $array);
if (!$id)
return $find.' not found';
if (isset($array[$id + $offset]))
return $array[$id + $offset];
return $find.' is first in array';
}
You can also set the offset to be different from 1 previous.
Related
This is my code:
function get_random(){
$filter_word = '1,2,3,4,5,6,7,8,9';
$array = explode(',', $filter_word);
$randomKeys = array_rand($array, 2);
$str = '';
foreach($randomKeys as $key){
$str = $array[$key];
}
return $str;
}
The problem that if I used array_rand i must know the number of elements to can add the number in array_rand and I can't know something like this (it's a data stored into the database) so if the elements are less than two it gives me an error:
Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array
Is there a better way to make this?
you can use count() before using array_rand-
function get_random(){
$filter_word = '1,2,3,4,5,6,7,8,9';
$array = explode(',', $filter_word);
$str = '';
if(count($array)>1){
$randomKeys = array_rand($array, 2);
foreach($randomKeys as $key){
$str = $array[$key];
}
}
else{
$str = $filter_word;
}
return $str;
}
I suppose you are looking for something like this:
$randCount = rand(1, count($array));
$randomKeys = array_rand($array, $randCount);
So here is situation let's imagine a string and an array:
$str = 'Sample string';
$arr = array('sample', 'string')
What would be the best way to determine if the given string has all of the words contained in the array? String can be longer, and has additional words, it does not matter. The only thing I need, is a function that given a string and an array would return true, if string contains every single word that is in array (case and order I'm which they appear does not matter)
You can simply use str_word_count with extra parameter 1 like as
$str = 'Sample string';
$arr = array('sample', 'string');
$new_arr = array_intersect(array_map('strtolower',str_word_count($str,1)),$arr);
print_r($new_arr);
Output:
Array
(
[0] => sample
[1] => string
)
Demo
Try this one:
<?php
$words = array('sample', 'string');
$str = 'sample string';
strtolower($str);
$strArr = explode(' ',$str);
$wordfound = false;
foreach ($strArr as $k => $v) {
if (in_array($v,$words)) {$wordfound = true; break;}
foreach($words as $kb => $vb) {
if (strstr($v, $kb)) $wordfound = true;
break;
}
}
if ($wordfound) {
echo 'Found!';
}
else echo 'Not found!';
If performance matters, I would use an associative array:
$words = array_flip(preg_split('/\\s+/', strtolower($str)));
$result = true;
foreach ($arr as $find) {
if (!isset($words[$find])) {
$result = false;
break;
}
}
Demo
Try this out.
$strArray = explode(" ", $str);
$result = array_intersect($strArray, $arr);
if(sizeof($result) == sizeof($arr)){
return TRUE;
}else{
return FALSE;
}
if this don't work, then try swapping the inputs in array_intersect($arr, $strArray)
You can add other functions to make all lowercase before comparing to give it a finishing touch.
$str = 'Sample string';
$str1=strtolower($str);
$arr = array(
'sample',
'string'
);
foreach($arr as $val)
{
if(strpos($str1,strtolower($val)) !== false)
{
$msg='true';
}
else
{
$msg='false';
break;
}
}
echo $msg;
My string is like the following format:
$string =
"name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
I want to split the string like the following:
$str[0] = "name=xxx&id=11";
$str[1] = "name=yyy&id=12";
$str[2] = "name=zzz&id=13";
$str[3] = "name=aaa&id=10";
how can I do this in PHP ?
Try this:
$matches = array();
preg_match_all("/(name=[a-zA-Z0-9%_-]+&id=[0-9]+)/",$string,$matches);
$matches is now an array with the strings you wanted.
Update
function get_keys_and_values($string /* i.e. name=yyy&id=10 */) {
$return = array();
$key_values = split("&",$string);
foreach ($key_values as $key_value) {
$kv_split = split("=",$key_value);
$return[$kv_split[0]] = urldecode($kv_split[1]);
}
return $return;
}
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
$arr = split("name=", $string);
$strings = aray();
for($i = 1; $i < count($arr), $i++){
$strings[$i-1] = "name=".substr($arr[$i],0,-1);
}
The results will be in $strings
I will suggest using much simpler term
Here is an example
$string = "name=xxx&id=11;name=yyy&id=12;name=zzz&id=13;name=aaa&id=10";
$arr = explode(";",$string); //here is your array
If you want to do what you asked, nothing more or less , that's explode('&', $string).
If you have botched up your example and you have a HTTP query string then you want to look at parse_str().
Is there a built in function in PHP that would combine 2 strings into 1?
Example:
$string1 = 'abcde';
$string2 = 'cdefg';
Combine to get: abcdefg.
If the exact overlapping sequence and the position are known, then it is possible to write a code to merge them.
TIA
I found the substr_replace method to return funny results.
Especially when working with url strings. I just wrote this function.
It seems to be working perfectly for my needs.
The function will return the longest possible match by default.
function findOverlap($str1, $str2){
$return = array();
$sl1 = strlen($str1);
$sl2 = strlen($str2);
$max = $sl1>$sl2?$sl2:$sl1;
$i=1;
while($i<=$max){
$s1 = substr($str1, -$i);
$s2 = substr($str2, 0, $i);
if($s1 == $s2){
$return[] = $s1;
}
$i++;
}
if(!empty($return)){
return $return;
}
return false;
}
function replaceOverlap($str1, $str2, $length = "long"){
if($overlap = findOverlap($str1, $str2)){
switch($length){
case "short":
$overlap = $overlap[0];
break;
case "long":
default:
$overlap = $overlap[count($overlap)-1];
break;
}
$str1 = substr($str1, 0, -strlen($overlap));
$str2 = substr($str2, strlen($overlap));
return $str1.$overlap.$str2;
}
return false;
}
Usage to get the maximum length match:
echo replaceOverlap("abxcdex", "xcdexfg"); //Result: abxcdexfg
To get the first match instead of the last match call the function like this:
echo replaceOverlap("abxcdex", "xcdexfg", “short”); //Result: abxcdexcdexfg
To get the overlapping string just call:
echo findOverlap("abxcdex", "xcdexfg"); //Result: array( 0 => "x", 1 => "xcdex" )
It's possible using substr_replace() and strcspn():
$string1 = 'abcde';
$string2 = 'cdefgh';
echo substr_replace($string1, $string2, strcspn($string1, $string2)); // abcdefgh
No, there is no builtin function, but you can easily write one yourself by using substr and a loop to see how much of the strings that overlap.
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.