PHP replace a character in string fetched from mysql - php

I'm trying to replace a string which contains value with operator : like "2456:72" to "2456.72" where data is fetched from mysql, I tried using str_replace which sucks. $row_loop3["Tot_minutes"] is the row which I should replace the character, please find my code:
$mysqli = new mysqli("172.16.10.102", "******", "RND#ISO-3306", "eTrans");
if (!$mysqli->multi_query("call sp_get_Android_Online_minutes_Chart ('2015-01-01','2016-01-30')")) {
$response["success"] = 0;
}
do {
if ($res_loop3 = $mysqli->store_result()) {
$response_loop3["minutes"] = array();
$find = ":";
$re = ".";
while ($row_loop3 = $res_loop3->fetch_assoc()) {
$j = 5;
$value_loop3 = array();
$value_loop3["File_Day"] = $row_loop3["edit_date"];
$value_loop3["File_Minutes"] = $row_loop3["FileDay"];
$val["Tot1_Minutes"] = $row_loop3["Tot_minutes"];
$value_loop3["Total_Minutes"] = str_replace($val, $find, $re); //value which I should replace : with .
array_push($response_loop3["minutes"], $value_loop3);
$response_loop3["success"] = 1;
}
echo $merger = json_encode(array_merge($response, $response_loop2, $response_loop3));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
please help me, thanks in advance

You are not making variable instead you are making associative array.
change this
$val["Tot1_Minutes"] = $row_loop3["Tot_minutes"];
to
$val= $row_loop3["Tot_minutes"];
and also order in str function to
$val = $row_loop3["Tot_minutes"];
$value_loop3["Total_Minutes"]=str_replace($find,$re,$val);

str_replace should be used in this way:
str_replace( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
The function's argument are search, replace, and subject, so for your case should be like : str_replace($find,$re,$val)

Related

php strpos and approximate match with 1 character difference

I searched the system but couldn't find any help I could understand on this, so here goes...
I need to find an approximate match for a string in php.
Essentially I'm checking that all the $names are in the $cv string and if not it sets a flag to true.
foreach( $names as $name ) {
if ( strrpos( $cv, $name ) === false ) {
$nonameincv = true;
}
}
It works fine. However, I had a case of $cv = "marie_claire" and a $name = "clare" which set the flag (of course) but which I'd have liked for strpos to have "found" as it were.
Is it possible to do an approximate match so that if a string has 1 extra letter anywhere in it, it would match? For example so that:
$name = "clare" is found in $cv = "marie_claire"
$name = "caire" is found in $cv = "marie_claire"
$name = "laire" is found in $cv = "marie_claire"
and so on...
Note: This will work perfectly fine when there is difference of 1 character, as stated in question above.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$stringToSearch="mare";
$wholeString = "marie_claire";
$wholeStringArray= str_split($wholeString);
for($x=0;$x<strlen($wholeString);$x++)
{
$tempArray=$wholeStringArray;
unset($tempArray[$x]);
if(strpos(implode("", $tempArray), $stringToSearch)!==false)
{
echo "Found: $stringToSearch in ".implode("", $wholeStringArray);
break;
}
}
Try this, not considering performance, but would work for your case.You can play with the the number of different chars deviation you want to accept.
$names = array("clare", "caire", "laire");
$cv = "marie_claire";
foreach( $names as $name ) {
$sname = str_split($name);
$words = explode('_', $cv);
foreach($words as $word) {
$sword = str_split($word);
$result = array_diff($sword, $sname);
if(count($result) < 2)
echo $name. ":true\r\n";
}
}

How to get value of specified part of pattern from URL string like MVC route using php?

i have these variables:
$pathPattern = '/catalog/{name}/{id}';
$pathRealUrl = '/catalog/test-product/12343';
The $pathPattern is dynamic, from a json file.
The $pathRealUrl is the url.
Now I need to create this two variables:
$name = 'test-product';
$id = 12343;
Note that the $pathPattern can have many variables
and also that {name} and {id} can have different name ( like {xxx} or {pippo} ), other sample:
$pathPattern = '/home/test/{hello}';
$pathRealUrl = '/home/test/alex';
The best way for archive this?
Split both string by / delimiter and loop through generated array from $pathPattern. In loop, get string that is between { and } and create variable named to it. At the end, set value of relevant index of $pathRealUrlArr in created variable.
$pathPatternArr = explode("/", $pathPattern);
$pathRealUrlArr = explode("/", $pathRealUrl);
foreach($pathPatternArr as $key=>$item){
if (preg_match("/^{(\w+)}$/", $item, $matches))
${$matches[1]} = $pathRealUrlArr[$key];
}
echo $name, $id;
See result in demo
You can shorten the code like bottom
foreach(explode("/", $pathPattern) as $key=>$item){
if (preg_match("/^{(\w+)}$/", $item, $matches))
${$matches[1]} = explode("/", $pathRealUrl)[$key];
}
echo $name, $id;
If the count of the number of values between the slashes will remain same or the position of the {name}/{id} will remain same then you can use explode to split the string by "/" and the get the desired values from the resultant array.
e.g.
$pathRealUrl = '/catalog/test-product/12343';
$array = explode("/",$pathRealUrl );
$id = $array[count($array)-1];
$name = $array[count($array)-2];
Ideone link : http://ideone.com/aNpxEJ
Hope it helps. :)
$pathPattern = '/catalog/{name}/{id}';
$pathRealUrl = '/catalog/test-product/12343';
$b = explode("/", $pathPattern);
$e = explode("/", $pathRealUrl);
$i = 0;
foreach ($b as $v) {
${substr($v,1,-1)} = $e[$i];
$i++;
}
echo $name;
echo $id;
And:
$i = 0;
foreach (explode("/", $pathPattern) as $v) {
${substr($v,1,-1)} = explode("/", $pathRealUrl)[$i];
$i++;
}
Show demo

Change portion of value within an array knowing only part of string and restric

Before I got this answer
preg_replace("~(?<=$str&&).*~", '7', $str);
which is good but what if within the array I have a similar string mary&&5 and rosemary&&5 and I stricktly want to change only mary&&5 and not disturb the other array, is it posible? and how?
The question before was:
`$array = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8", etc..);`
and I know only the string before && which is username. $str = "mary&&"; Note that I don't know what is after &&
I want to know whether exist or not within the array, and if exist change the value to something new like mary&&7
`$isExists = preg_replace("some","some", $array);
if ($isExists){
echo "Its exists";
} else {
echo "Not exixts"
} ;`
How can I change the portion of the value after && in mary&&5 or completely change mary&&5 to mary&&7 since I don't know before hand the value mary&&5?
Thanks for your answer :)
`$name = "mary";
$res = "7";
$str = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8","rosemary&&5");
for ($i = 0; $i < count($str); ++$i) {
$r = preg_replace("~(?<=$name).*~",$res, $str);}`
$arr = array('josh&&3', 'mary&&5', 'cape&&4', 'doggy&&8', 'rosemary&&5');
$name = 'mary';
$number = '7';
$replacement = $name . '&&' . $number;
So, a way without regex:
foreach($arr as $k=>$v) {
if (explode('&&', $v)[0] === $name)
$arr[$k] = $replacement;
}
( or you can use strpos($v, $name . '&&') === 0 as condition)
a way with regex:
$arr = preg_filter('~\A' . $name . '&&\K.*~', $number, $arr);
(where \K removes all on the left from the match result, so the name and && aren't replaced)

Parsing a string in PHP

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().

Convert a String to Variable

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.

Categories