I have a series of strings that I have read in with fgets() from a .csv file, and then exploded into an array. The file has the csv standard double quotes. For example:
video
is one of the values that I am reading in. I need all instances of "" to be replaced by just ". I know that this is a simple solution, but I can't seem to wrap my head around the way that the escape characters would work.
Use str_replace:
$string = 'test';
$string = str_replace('""', '"', $string);
echo $string;
// Outputs: test
Related
I want to delete any dollar sign($) from a PHP variable only if it surrounds a word.
I know how to replace every $ with empty space to look like is deleted, for example:
<?php
$string = 'Hello $George$';
$string = str_replace('$', '', $string);
echo $string; // Prints: Hello George
?>
But the code above is also removing $ that are not surrounding a word, for example:
<?php
$string = 'Hello $George$, are you $ok?';
$string = str_replace('$', '', $string);
echo $string; // Prints Hello George, are you ok?
?>
I've been trying for many hours to solve this problem but didn't manage to puzzle it out, any help is appreciated.
First of all, i will answer your question
Use preg_replace instead, that is uses with a pattern that detects only those dollar signs, that are surrounding a word.
$string = preg_replace('/\$(\w+)\$/', '$1', $string);
Now an improvement for your code
As mentioned in the comments of your question, you would need to surround your string with single quotes (') to prevent PHP from replacing your words, that are prefixed by a dollar sign, with their corresponding variables.
A good source to understand the differences between double- and single-enquoted strings can be found from this question.
Recently ran into a very odd issue where my database contains strings with what appear to be normal whitespace characters but are in fact something else.
For instance, applying trim() to the string:
"TEST "
is getting me:
"TEST "
as a result. So I copy and paste the last character in the string and:
echo ord(' ');
194
194? According to ASCII tables that should be ┬. So I'm just confused at this point. Why does this character appear to be whitespace and how can I trim() characters like this when trim() fails?
It's more likely to be a two-byte 194 160 sequence, which is the UTF-8 encoding of a NO-BREAK SPACE codepoint (the equivalent of the entity in HTML).
It's really not a space, even though it looks like one. (You'll see it won't word-wrap, for instance.) A regular expression match for \s would match it, but a plain comparison with a space won't; nor will trim() remove it.
To replace NO-BREAK spaces with a normal space, you should be able to do something like:
$string = str_replace("\u{c2a0}", " ", $string);
or
$string = str_replace("\u{c2a0}", "", $string);
to remove them
You can try with :
PHP trim
$foo = "TEST ";
$foo = trim($foo);
PHP str_replace
$foo = "TEST ";
$foo = str_replace(chr(194), '', $foo);
IMPORTANT: You can try with chr(194).chr(160) or '\u00A0'
PHP preg_replace
$foo = "TEST ";
$foo = preg_replace('#(^\s+|\s+$)#', '', $foo);
OR (i'm not sure if it will work well)
$foo = "TEST ";
$foo = preg_replace('#[\xC2\xA0]#', '', $foo);
Had the same issue. Solved it with
trim($str, ' ' . chr(194) . chr(160))
You probably got the original data from Excel/CSV.. I'm importing from such format to my mysql db and it took me hours to figure out why it came padded and trim didn't appear to work (had to check every character in each CSV column string) but in fact it seems Excel adds chr(32) + chr (194) + chr(160) to "fill" the column, which at first sight, looks like all spaces at the end. This is what worked for me to have a pretty, perfect string to load into the db:
// convert to utf8
$value = iconv("ISO-8859-15", "UTF-8",$data[$c]);
// excel adds 194+160 to fill up!
$value = rtrim($value,chr(32).chr(194).chr(160));
// sanitize (escape etc)
$value = $dbc->sanitize($value);
php -r 'print_r(json_encode(" "));'
"\u00a0"
$string = str_replace("\u{00a0}", "", $string); //not \u{c2a0}
I needed to trim my string in PHP and was getting the same results.
After discovering the reason via Mark Bakers answer, I used the following in place of trim:
// $str = trim($str); // won't strip UTF-8 encoded nonbreaking spaces
$str = preg_replace('/^(\\s|\\xC2\\xA0)+|(\\s|\\xC2\\xA0)+$/', '', $str);
Thought I should contribute an answer of my own since it has now become clear to me what was happening. The problem originates dealing with html which contains a non-breaking space entity, . Once you load the content in php's DOMDocument(), all entities are converted to their decoded values and upon parsing the it you end up with a non-breaking space character. In any event, even in a different scenario, the following method is another option for converting these to regular spaces:
$foo = str_replace(' ',' ',htmlentities($foo));
This works by first converting the non-breaking space into it's html entity, and then to a regular space. The contents of $foo can now be easily trimmed as normal.
I have some plain text used to generate html, this is the text:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string'with'bad'quotes'');">
lots of stuff
The structure of the text is always the same because that text is in turn generated, but the last string used as an argument to the javascript function can change, it may have any number of single quotes or not at all. I want to replace those quotes with \' so that the result is:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string\'with\'bad\'quotes\'');">
lots of stuff
I got this far:
onclick="javascript:do_things\('.*', '(.*)'\)
which gives me this match:
string'with'bad'quotes'
But I haven't been able to match the quotes inside, I mean, I could match a quote with .*'.*, but how do I match any number of quotes in any position?
Thanks
How about this?
$string = 'lots of stuff
<a onclick="javascript:do_things(\'http://somelink.to.something.com\', \'string\'with\'bad\'quotes\'\');">
lots of stuff';
echo preg_replace_callback('~(<a\h*onclick="javascript:do_things\(\'.*?\',\h*\')(.*)(\'\);">)~', function($match){
return $match[1] . str_replace("'", "\'", $match[2]) . $match[3];}, $string);
Output:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string\'with\'bad\'quotes\'');">
lots of stuff
Regex101 Demo: https://regex101.com/r/rM5mM3/3
We capture the second part of the function then execute a replacement on all single quotes in the found string.
This question already has answers here:
How do I replace certain parts of my string?
(5 answers)
Closed last month.
Is there a anyway to remove apostrophe from a string in php?
example:- If string is Mc'win then it should be shown as Mcwin
$Str = "Mc'win";
/*
some code to remove the apostrophe
*/
echo $Str; // should display Mcwin
You can use str_replace.
$Str = str_replace('\'', '', $Str);
or
$Str = str_replace("'", '', $Str);
This will replace all apostrophes with nothing (the 2nd argument) from $Str. The first example escapes the apostrophe so str_replace will recognize it as the character to replace and not part of the enclosure.
If your variable has been sanitized, you may be frustrated to find you can't remove the apostrophe using $string = str_replace("'","",$string);
$string = "A'bcde";
$string = filter_var($string, FILTER_SANITIZE_STRING);
echo $string." = string after sanitizing (looks the same as origin)<br>";
$string = str_replace("'","",$string);
echo $string." ... that's odd, still has the apostrophe!<br>";
This is because sanitizing converts the apostrophe to ' , but you may not notice this, because if you echo the string it looks the same as the origin string.
You need to modify your replace search characters to '
which works after sanitizing.
$string = str_replace("'","",$string);
in my case, i got single quote issue when i wanted to store it to database (in my case MySQL). So, i remove the single quotes using this method
str_replace("'", "", trim($_GET["message"]))
But, the problems comes. Some data required us to have single quotes. So, instead of removing the quotes I try to save the single quotes (escaping single quotes) so it can be used in the future (in my case at Android)
My Idea is to replace from ' to ''.
So here is the final
$content = str_replace("'", "''", trim($_GET["message"])); // double quotes for escape single quotes
This answer is for someone that persist problem like me. I got better solution. Cheers!
I have a PHP page which gets text from an outside source wrapped in quotation marks. How do I strip them off?
For example:
input: "This is a text"
output: This is a text
Please answer with full PHP coding rather than just the regex...
This will work quite nicely unless you have strings with multiple quotes like """hello""" as input and you want to preserve all but the outermost "'s:
$output = trim($input, '"');
trim strips all of certain characters from the beginning and end of a string in the charlist that is passed in as a second argument (in this case just "). If you don't pass in a second argument it trims whitespace.
If the situation of multiple leading and ending quotes is an issue you can use:
$output = preg_replace('/^"|"$/', '', $input);
Which replaces only one leading or trailing quote with the empty string, such that:
""This is a text"" becomes "This is a text"
$output = str_replace('"', '', $input);
Of course, this will remove all quotation marks, even from inside the strings. Is this what you want? How many strings like this are there?
The question was on how to do it with a regex (maybe for curiosity/learning purposes).
This is how you would do that in php:
$result = preg_replace('/(")(.*?)(")/i', '$2', $subject);
Hope this helps,
Buckley