trim function is giving unexpected values php - php

I have taken the following inputs
$file = 'D:/php/testapp/ta_bles.json';
$table = trim(end(explode("/", $file)), '.json');
but instead of giving ta_bles as the output it is giving ta_ble
can any one help me what is happening
but when i use the following logic it gave expected results
$table = str_replace('.json', '', end(explode("/", $file)));

The reason why it doesn't work as expected is because the second argument to trim() (and related functions) is used as a character set; so in the extreme example of "json.json" you will end up with an empty string because it trims each character separately.
You could compare such an operation to this:
preg_replace('/^[.json]+|[.json]+$/', '', $str);
To just get "tables" you should use pathinfo() instead of trying to roll your own:
$table = pathinfo('d:/php/testapp/tables.json', PATHINFO_FILENAME);

Related

Array and substring php

//array data
{
$results[] = $result;
$SiteID=$result["site_id"];
$pay_sale_id=$result["pay_sale_id"];
$pay_payment_info=$result["pay_payment_info"];
$payNo= substring_index(substring_index('$result["pay_payment_info"]', '$USER=', -1), '~$TAGROLE', 1);
}
The content of pay_payment_info is as follows
#$TAG=6F0000173~$USER=james~$TAGROLE=0
I want to extract only the user info, but i get error:
Fatal error: Call to undefined function substring_index() in line
Considering the user info always begins with ~$USER= and ends with a ~ we can get the result using simple regex:
preg_match('/\~\$USER=(?<user>[^~]+)/', $pay_payment_info, $match);
var_dump($match['user']);
As previous comments said - there is no such function like substring_index in core PHP
This question is possible duplicate of following Php get string between tags
topic
Here is working example with usage of strpos http://php.net/manual/pl/function.strpos.php
and substr http://php.net/manual/pl/function.substr.php
$var = '$TAG=6F0000173~$USER=james~$TAGROLE=0';
$m = substr($var, strpos($var, '~$USER=')+7);
var_dump($m); //returns string(16) "james~$TAGROLE=0"
$m = substr($m, 0, strpos($m, '~$'));
var_dump($m); //returns string(5) "james"
it seems that the problem is you have no substring_index() function or method, yet you attempt to invoke it twice.
I am not sure why you use the ~ as a delimiter but that should be ok, although using a , would have resulted in less work; each of the attributes of your querystring would have been able to be addressed directly then.
what you want to do is use the php version of split() which is explode() here is a link to the manual.
what you want to do is split the inc string:
$aUserInfo = explode('~', $result['pay_payment_info']);
now you have an array. loop through it and make it like you want:
$result = array();
foreach($aUserInfo as $v){
$aTmp = explode('=',$v);
$result[$aTmp[0]] = $aTmp[1];
}
at the end of this you have an array with keys as keys and their respective values as values, i.e.
$result = array( 'tag' => '6F0000173',
'user'=> 'James',
'tagrole'=> 0 );
The error tells you exactly why it is an error: substring_index is not a valid/native PHP function... you can define your own function of substring_index, though.
However, given the string:
$TAG=6F0000173~$USER=james~$TAGROLE=0
to get the $USER=james part, you can use explode as follows--
$payNo = explode("~", $result["pay_payment_info"])
Now, you have the $USER info in $payNo[1]
If you want to go even further and just get the value of what $USER value is, then you can use PHP's native substr function:
$justUserPart = substr($payNo[1], strpos($payNo[1], "=")+1);
echo $justUserPart;
Please Note: The above assumes that you will always have the string in the format of
$TAG=...~$USER=...~$TAGROLE=...

PHP: remove last comma of a multipolygon

I have following issue:
I import WKT dynamicaly from DB into WKT Wicket Javascript library. I must do some substitutions to fit the WKT correctly. Since mysql fetches WKT AsText(SHAPE) i recive several arrays e.g. POLYGON((xxxx)),POLYGON((yyyy)) and so on.
First, I had to remove all "POLYGON" doing
$str = preg_replace('/^POLYGON/', '', $WKT[1]);
and add MULTIPOLYGON before <?php
tag in the wicket. It works.
Second, I must add comma between polygons, preicisely between "))((" brackets:
$str2 = str_replace(array('((', '))'), array('((', ')),'), $str);
It works but last comma remains what "slightly" deforms my multipolygon:
MULTIPOLYGON((xxx)),((yyy)),((zzz)),
How can I remove last comma?
I would be thankful for every regex or some other solution which can solve my problem.
In any string, you can remove the last X if you are sure that no X follows. So, you can use a negative lookahead: (,)(?!.*,), as seen here and replace it with empty string.
$result = preg_replace('/(,)(?!.*,)/', '', $str)
This doesn't look at the context though, it will just remove the last comma of any string, no matter where it is.
Thank you both - your answers were right and very helpful.
The problem was not string replacement. It was more the data fetching from DB.
Mysqli_fetch_array and mysqli_fetch_assoc return stringstringsring or arrayarrayarray for 3 rows fetched. That is why all commas were replaced.
I changed to mysqli_fetch_all ,then did minor replacements for each row (as array) and implode each one as variable. After i merged them into single variable, then I could apply your solutions. It is not sofisticated solution, but if it is packed into function it'll be fine.
($WKT = mysqli_fetch_all($result)) {
$str = preg_replace('/POLYGON/', '', $WKT[0]);
$str1 = preg_replace('/POLYGON/', '', $WKT[1]);
$str2 = preg_replace('/POLYGON/', '', $WKT[2]);
$str3 = implode($str);
$str4 = implode($str1);
$str5 = implode($str2);
$str6 = $str3 . $str4 . $str5;
$str7 = preg_replace('/\)\)/', ')),', $str6);
$str8 = rtrim($str7, ",");
echo $str8;
}

Parse a string in php

I am wondering how I can parse this string to get a certain name or string. What I need to parse is:
items/category/test.txt
To get it with out test.txt of course there will be different names so I can't just replace it.
I need the result to be:
items/category/
Also how can I parse it to get /category/ only?
Use PHP's pathinfo() function:
http://php.net/manual/en/function.pathinfo.php
$info = pathinfo('items/category/test.txt');
$dirPath = $info['dirname'];
// OR
$dirPath = pathinfo('items/category/test.txt', PATHINFO_DIRNAME);
// Output: items/category
Use explode to get the above string as array
$string = "tems/category/test.txt";
$string_array = explode("/",$string);
print_r($string_array); // Will Output above as an array
// to get items/category/
$var = $string_array[0].'/'.$string_array[1];
echo $var; //will output as items/category/
$var2 = '/'.$string_array[1].'/';
echo $var2; //will output as /category/
I believe your best chance is explode("/","items/category/test.txt") .
This will splice the string every time it finds / returning an array, whereas implode (join is an alias of it) will join an array of strings, so
$spli=explode("/","items/category/test.txt");
implode($spli[0],$spli[1]);
Should do the trick for the first case, returning items/category
For category alone, $spli[1] is enough.
Of course, you may pass the string as a variable, for instance
$foo="items/category/test.txt;"
explode("/",$foo);
etc.

Regex not displaying well whe using PHP preg_quote

Hi Im trying to concatinate a string before converting that string into regex in PHP, but the problem is it's not displaying as expected. I've been searching using google and found out about preg_quote, problem is it's not working well.
Here is my example:
$mystring = "banana"; // put this to a variable assume this value is dynamic
$regex_str = "/^"$mystring"\-[a-z0-9]\-[a-z0-9]$/";
//Im expecting expecting /^banana\-[a-z0-9]\-[a-z0-9]$/
$regex = preg_quote($regex_str);
but what I am getting is:
/\^banana\\\-\[a\-z0\-9\]\\\-\[a\-z0\-9\]\$/
and always returning the wrong value.
Call preg_quote() on the string you're adding before you add it into the regex:
$mystring = "banana";
$regex_str = "/^" . preg_quote($mystring, "/") . "\-[a-z0-9]\-[a-z0-9]$/";

very large php string magically turns into array

I am getting an "Array to string conversion error on PHP";
I am using the "variable" (that should be a string) as the third parameter to str_replace. So in summary (very simplified version of whats going on):
$str = "very long string";
str_replace("tag", $some_other_array, $str);
$str is throwing the error, and I have been trying to fix it all day, the thing I have tried is:
if(is_array($str)) die("its somehow an array");
serialize($str); //inserted this before str_replace call.
I have spent all day on it, and no its not something stupid like variables around the wrong way - it is something bizarre. I have even dumped it to a file and its a string.
My hypothesis:
The string is too long and php can't deal with it, turns into an array.
The $str value in this case is nested and called recursively, the general flow could be explained like this:
--code
//pass by reference
function the_function ($something, &$OFFENDING_VAR, $something_else) {
while(preg_match($something, $OFFENDING_VAR)) {
$OFFENDING_VAR = str_replace($x, y, $OFFENDING_VAR); // this is the error
}
}
So it may be something strange due to str_replace, but that would mean that at some point str_replace would have to return an array.
Please help me work this out, its very confusing and I have wasted a day on it.
---- ORIGINAL FUNCTION CODE -----
//This function gets called with multiple different "Target Variables" Target is the subject
//line, from and body of the email filled with << tags >> so the str_replace function knows
//where to replace them
function perform_replacements($replacements, &$target, $clean = TRUE,
$start_tag = '<<', $end_tag = '>>', $max_substitutions = 5) {
# Construct separate tag and replacement value arrays for use in the substitution loop.
$tags = array();
$replacement_values = array();
foreach ($replacements as $tag_text => $replacement_value) {
$tags[] = $start_tag . $tag_text . $end_tag;
$replacement_values[] = $replacement_value;
}
# TODO: this badly needs refactoring
# TODO: auto upgrade <<foo>> to <<foo_html>> if foo_html exists and acting on html template
# Construct a regular expression for use in scanning for tags.
$tag_match = '/' . preg_quote($start_tag) . '\w+' . preg_quote($end_tag) . '/';
# Perform the substitution until all valid tags are replaced, or the maximum substitutions
# limit is reached.
$substitution_count = 0;
while (preg_match ($tag_match, $target) && ($substitution_count++ < $max_substitutions)) {
$target = serialize($target);
$temp = str_replace($tags,
$replacement_values,
$target); //This is the line that is failing.
unset($target);
$target = $temp;
}
if ($clean) {
# Clean up any unused search values.
$target = preg_replace($tag_match, '', $target);
}
}
How do you know $str is the problem and not $some_other_array?
From the manual:
If search and replace are arrays, then str_replace() takes a value
from each array and uses them to search and replace on subject. If
replace has fewer values than search, then an empty string is used for
the rest of replacement values. If search is an array and replace is a
string, then this replacement string is used for every value of
search. The converse would not make sense, though.
The second parameter can only be an array if the first one is as well.

Categories