PHP implode's strangely adds white chars to its output - why? - php

I have very, very odd problem with PHP's implode function. It surprisingly adds some white characters (spaces) to one of array's elements.
Here is my code:
$cities = array(...,5792753,...);
$where .= ' AND gr.geo_city IN(' . implode(',', $cities) . ') ';
//it displays something like: ... AND gr.geo_city IN(...,5 792753,...)
//but it should display: ... AND gr.geo_city IN(...,5792753,...)
//PLEASE NOTE SPACES IN THE EXAMPLE ABOVE!!
echo $where;
I have done some debugging and it seems the original values do not contain any white chars. Here is the code I've used to check it:
foreach($cities as $ct)
{
if(strpos($ct,'792753') !== FALSE)
echo $ct;//it displays 5792753, not 5...792753
}
Why does it add these spaces there? Is it some known bug of the implode function?
Thanks!

You almost certainly have those characters in your original array values. As the commenters have said, implode() does nothing strange... Check your data again for hidden tabs or spaces, or other whitespace characters.

If you want to make sure there are no whitespaces, better strip them with some php functions (str_replace, trim, or reg_exp functions).
Implode does not add anything but the given separator.

Related

Create a function to find a specific word in the title

I have the following title formation on my website:
It's no use going back to yesterday, because at that time I was... Lewis Carroll
Always is: The phrase… (author).
I want to delete everything after the ellipsis (…), leaving only the sentence as the title. I thought of creating a function in php that would take the parts of the titles, throw them in an array and then I would work each part, identifying the only pattern I have in the title, which is the ellipsis… and then delete everything. But when I do that, in the X space of my array, it returns the following:
was...
In position 8 of the array comes the word and the ellipsis and I don't know how to find a pattern to delete the author of the title, my pattern was the ellipsis. Any idea?
<?php
$a = get_the_title(155571);
$search = '... ';
if(preg_match("/{$search}/i", $a)) {
echo 'true';
}
?>
I tried with the code above and found the ellipsis, but I needed to bring it into an array to delete the part I need. I tried something like this:
<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
global $wpdb;
$title_array = explode(' ', get_the_title(155571));
$search = '... ';
if (array_key_exists("/{$search}/i",$title_array)) {
echo "true";
}
?>
I started doing it this way, but it doesn't work, any ideas?
Thanks,
If you use regex you need to escape the string as preg_quote() would do, because a dot belongs to the pattern.
But in your simple case, I would not use a regex and just search for the three dots from the end of the string.
Note: When the elipsis come from the browser, there's no way to detect in PHP.
$title = 'The phrase... (author).';
echo getPlainTitle($title);
function getPlainTitle(string $title) {
$rpos = strrpos($title, '...');
return ($rpos === false) ? $title : substr($title, 0, $rpos);
}
will output
The phrase
First of all, since you're working with regular expressions, you need to remember that . has a special meaning there: it means "any character". So /... / just means "any three characters followed by a space", which isn't what you want. To match a literal . you need to escape it as \.
Secondly, rather than searching or splitting, you could achieve what you want by replacing part of the string. For instance, you could find everything after the ellipsis, and replace it with an empty string. To do that you want a pattern of "dot dot dot followed by anything", where "anything" is spelled .*, so \.\.\..*
$title = preg_replace('/\.\.\..*/', '', $title);

PHP sort input textarea list into numbered list

I have a form text area that I want users to paste data into, which then when submitted is processed with some PHP and returns the list but numbered every carraige return.
Eg, user inputs;
Ben
Chris
Morris
PHP returns;
1=Ben
2=Chris
3=Morris
Tried some preg_replace_callback technique but couldn't fathom it. Not too familiar with how it works though;
$list = $_POST["list"]; $count = 0;
preg_replace_callback('\r\n', 'rep_count', $list);
function rep_count($matches) {
global $count;
return '<br />' . $count++;
}
echo $list;
You've got a couple errors:
preg_replace_callback('\r\n', 'rep_count', $list);
^^^^^^
Your pattern is incorrect - it's missing the delimiters, and should be /\r\n/. As well, using '-quoted strings for the pattern makes the \r and \n just be escaped alphabetical characters - '-quoted strings have no "metachars" like newlines and carriage returns.
Basically you need
preg_replace_callback("/\r\n/", 'rep_count', $list);
Note the " quotes, and the / delimeters.

php string replace by str_replace issue

i made a function to replace a words in a string by putting new words from an array.
this is my code
function myseo($t){
$a = array('me','lord');
$b = array('Mine','TheLord');
$theseotext = $t;
$theseotext = str_replace($a,$b, $theseotext);
return $theseotext;
}
echo myseo('This is me Mrlord');
the output is
This is Mine MrTheLord
and it is wrong it should be print
This is Mine Mrlord
because word (Mrlord) is not included in the array.
i hope i explained my issue in good way. any help guys
regards
According to the code it is correct, but you want it to isolate by word. You could simply do this:
function myseo($t){
$a = array(' me ',' lord ');
$b = array(' Mine ',' TheLord ');
return str_replace($a,$b, ' '.$t.' ');
}
echo myseo('This is me Mrlord');
keep in mind this is kind of a cheap hack since I surround the replace string with empty spaces to ensure both sides get considered. This wouldn't work for punctuated strings. The alternate would be to break apart the string and replace each word individually.
str_replace doesn't look at full words only - it looks at any matching sequence of characters.
Thus, lord matches the latter part of Mrlord.
use str_ireplace instead, it's case insensitive.

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

PHP - Sanitise a comma separated string

What would be the most efficient way to clean a user input that is a comma separated string made entirely on numbers - e.g
2,40,23,11,55
I use this function on a lot of my inputs
function clean($input){ $input=mysql_real_escape_string(htmlentities($input,ENT_QUOTES)); return $input; }
And on simple integers I do:
if (!filter_var($_POST['var'], FILTER_VALIDATE_INT)) {echo('error - bla bla'); exit;}
So should I explode it and then check every element of the array with the code above or maybe replace all occurrences of ',' with '' and then check the whole thing is a number? What do you guys think?
if (ctype_digit(str_replace(",", "", $input))) {
//all ok. very strict. input can only contain numbers and commas. not even spaces
} else {
//not ok
}
If it is CSV and if there might be spaces around the digits or commas and maybe even some quotation marks better use a regex to check if it matches
if (!preg_match('/\A\d+(,\d+)*\z/', $input)) die('bad input');
If you want to transform a comma-separated list instead of simply rejecting it if it's not formed correctly, you could do it with array_map() and avoid writing an explicit loop.
$sanitized_input = implode(",", array_map("intval", explode(",", $input)));
I would filter instead of error checking on simple input, though only 'cause I'm lazy, I suppose, and usually in a web context there's way too many cases to handle on what could be coming in that I wouldn't expect: Simple filter below.
<?php
$input = '234kljsalkdfj234a,a, asldkfja 345345sd,f jasld,f234l2342323##$##';
function clean($dirty){ // Essentially allows numbers and commas, just strips everything else.
return preg_replace('/[^0-9,]/', "", (string) $dirty);
}
$clean = clean($input);
echo $clean;
// Result: 234234,,345345,,2342342323
// Note how it doesn't deal with adjacent filtered-to-empty commas, though you could handle those in the explode. *shrugs*
?>
Here's the code and the output on codepad:
http://codepad.org/YfSenm9k

Categories