PHP: remove last comma of a multipolygon - php

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;
}

Related

preg_replace with a word in an array

I am trying to use certain words in a array called keywords, which will be used to be replaced in a string by "as".
for($i = 0; $i<sizeof($this->keywords[$this->lang]); $i++)
{
$word = $this->keywords[$this->lang][$i];
$a = preg_replace("/\b$word\b/i", "as",$this->code);
}
It works with if I replace the variable $word with something like /\bhello\b/i, which then would replace all hello words with "as".
Is the approach am using even possible?
Before to be a pattern, it's a double quoted string, so variables will be replaced, it's not the problem.
The problem is that you use a loop to change several words and you store the result in $a:
the first iteration, all the occurences of the first word in $this->code are replaced and the new string is stored in $a.
but the next iteration doesn't reuse $a as third parameter to replace the next word, but always the original string $this->code
Result: after the for loop $a contains the original string but with only the occurences of the last word replaced with as.
When you want to replace several words with the same string, a way consists to build an alternation: word1|word2|word3.... It can easily be done with implode:
$alternation = implode('|', $this->keywords[$this->lang]);
$pattern = '~\b(?:' . $alternation . ')\b~i';
$result = preg_replace($pattern, 'as', $this->code);
So, when you do that, the string is parsed only once and all the words are replaced in one shot.
If you have a lot of words and a very long string:
Testing a long alternation has a significant cost. Even if the pattern starts with \b that highly reduces the possible positions for a match, your pattern will have hard time to succeed and more to fail.
Only in this particular case, you can use this another way:
First you define a placeholder (a character or a small string that can't be in your string, lets say §) that will be inserted in each positions of word boundaries.
$temp = preg_replace('~\b~', '§', $this->code);
Then you change all the keywords like this §word1§, §word2§ ... and you build an associative array where all values are the replacement string:
$trans = [];
foreach ($this->keywords[$this->lang] as $word) {
$trans['§' . $word . '§'] = 'as';
}
Once you have do that you add an empty string with the placeholder as key. You can now use the fast strtr function to perform the replacement:
$trans['§'] = '';
$result = strtr($temp, $trans);
The only limitation of this technic is that it is case-sensitive.
it will work if you keep it like bellow:
$a = preg_replace("/\b".$word."\b/i", "as",$this->code);

PHP trouble with preg_match

I thought I had this working; however after further evaluation it seems it's not working as I would have hoped it was.
I have a query pulling back a string. The string is a comma separated list just as you see here:
(1,145,154,155,158,304)
Nothing has been added or removed.
I have a function that I thought I could use preg_match to determine if the user's id was contained within the string. However, it appears that my code is looking for any part.
preg_match('/'.$_SESSION['MyUserID'].'/',$datafs['OptFilter_1']))
using the same it would look like such
preg_match('/1/',(1,145,154,155,158,304)) I would think. After testing if my user id is 4 the current code returns true and it shouldn't. What am I doing wrong? As you can see the id length can change.
It's better to have all your IDs in an array then checking if a desired ID is existed:
<?php
$str = "(1,145,154,155,158,304)";
$str = str_replace(array("(", ")"), "", $str);
$arr = explode(',', $str);
if(in_array($_SESSION['MyUserID'], $arr))
{
// ID existed
}
As your string - In dealing with Regular Expressions, however it's not recommended here, below regex will match your ID if it's there:
preg_match("#[,(]$ID[,)]#", $str)
Explanations:
[,(] # a comma , or opening-parenthesis ( character
$ID # your ID
[,)] # a comma , or closing-parenthesis ) character

Remove certain character of string PHP

I need to remove the third character of a string. Here's what I tried.
$my_string['2'] = "";
This worked find, but when I tried to put this variable in a MySQL query, it returned errors.
What is the best way to remove a certain character (character 3 in my case) from a string?
Try out substr_replace.
For example:
$new_string = substr_replace($my_string, '', 2, 1);
Use an integer as index, not a string:
$my_string[2] = '';

How to remove commas between double quotes in PHP

Hopefully, this is an easy one. I have an array with lines that contain output from a CSV file. What I need to do is simply remove any commas that appear between double-quotes.
I'm stumbling through regular expressions and having trouble. Here's my sad-looking code:
<?php
$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';
$pattern = '(?<=\")/\,/(?=\")'; //this doesn't work
$revised_input = preg_replace ( $pattern , '' , $csv_input);
echo $revised_input;
//would like revised input to echo: "herp","derp,"hey get rid of these commas man",1234
?>
Thanks VERY much, everyone.
Original Answer
You can use str_getcsv() for this as it is purposely designed for process CSV strings:
$out = array();
$array = str_getcsv($csv_input);
foreach($array as $item) {
$out[] = str_replace(',', '', $item);
}
$out is now an array of elements without any commas in them, which you can then just implode as the quotes will no longer be required once the commas are removed:
$revised_input = implode(',', $out);
Update for comments
If the quotes are important to you then you can just add them back in like so:
$revised_input = '"' . implode('","', $out) . '"';
Another option is to use one of the str_putcsv() (not a standard PHP function) implementations floating about out there on the web such as this one.
This is a very naive approach that will work only if 'valid' commas are those that are between quotes with nothing else but maybe whitespace between.
<?php
$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';
$pattern = '/([^"])\,([^"])/'; //this doesn't work
$revised_input = preg_replace ( $pattern , "$1$2" , $csv_input);
echo $revised_input;
//ouput for this is: "herp","derp","hey get rid of these commas man",1234
It should def be tested more but it works in this case.
Cases where it might not work is where you don't have quotes in the string.
one,two,three,four -> onetwothreefour
EDIT : Corrected the issues with deleting spaces and neighboring letters.
Well, I haven't been lazy and written a small function to do exactly what you need:
function clean_csv_commas($csv){
$len = strlen($csv);
$inside_block = FALSE;
$out='';
for($i=0;$i<$len;$i++){
if($csv[$i]=='"'){
if($inside_block){
$inside_block=FALSE;
}else{
$inside_block=TRUE;
}
}
if($csv[$i]==',' && $inside_block){
// do nothing
}else{
$out.=$csv[$i];
}
}
return $out;
}
You might be coming at this from the wrong angle.
Instead of removing the commas from the text (presumably so you can then split the string on the commas to get the separate elements), how about writing something that works on the quotes?
Once you've found an opening quote, you can check the rest of the string; anything before the next quote is part of this element. You can add some checking here to look for escaped quotes, too, so things like:
"this is a \"quote\""
will still be read properly.
Not exactly an answer you've been looking for - But I've used it for cleaning commas in numbers in CSV.
$csv = preg_replace('%\"([^\"]*)(,)([^\"]*)\"%i','$1$3',$csv);
"3,120", 123, 345, 567 ==> 3120, 123, 345, 567

How to get part of a string in php

I have strings like:
t_est1_1
test213_4
tes_tsdfsdf_9
The common part of every string is the LAST underscore _ character.
I need to get the string before this character.
t_est1_12 --> test1
test213_4 --> test213
tes_tsdfsdf_9343 --> testsdfsdf
How can i achieve this in PHP?
Using the basic string functions strpos and substr.
http://fr.php.net/manual/fr/function.explode.php
$a = "abcdef_12345"
$b = array();
// $b[0] = "abcdef";
$b[0] = explode('_',$a,'1');
you can use preg_match function available in php
you need to write regular expression for that...
for example
to get this test1_12 ->> test1
$string='test1_12';
preg_match('((.+?)\_(.*))',$string,$match);
echo $match[1];
What you want is a simple explode, array_slice and implode, also using explode and end, you can get the "id" that is the common part too:
$description = implode('', array_slice(explode('_', $data), 0, -1));
$id = end(explode('_', $data));
As many _ you will have, you'll still be able to expode on them and retrieve the last item containing your id and the first items (0 to -1) will contain your description...

Categories