I was wondering how can I convert user submitted data that contains an & to and using PHP before its stored in the database.
Use str_replace
$after = str_replace('&', 'and', $before);
Note that this will perform a straightforward replacement, hence (as seen on ideone.com):
$text = "ben & jerry, vanilla&coke";
echo str_replace('&', 'and', $text)."\n";
# ben and jerry, vanillaandcoke
If you want to insert spaces when there previously wasn't, then you may want to use regular expressions function like preg_replace as follows:
echo preg_replace('/\s*&\s*/', ' and ', $text)."\n";
# ben and jerry, vanilla and coke
The pattern \s* is the regex pattern for "zero or more" (*) of whitespace characters (\s). In other words, this will replace &, including any preceding and following whitespaces (of any length), and replace it with ' and '.
You could do it like this:
$str = str_replace("&", "and", $str);
Using str_replace (if your data is in a single character encoding) or mb_ereg_replace (preceded by mb_regex_encoding) otherwise.
Note, however, that str_replace is (in this case) safe for UTF-8.
Related
I was scouring through SO answers and found that the solution that most gave for replacing multiple spaces is:
$new_str = preg_replace("/\s+/", " ", $str);
But in many cases the white space characters include UTF characters that include line feed, form feed, carriage return, non-breaking space, etc. This wiki describes that UTF defines twenty-five characters defined as whitespace.
So how do we replace all these characters as well using regular expressions?
When passing u modifier, \s becomes Unicode-aware. So, a simple solution is to use
$new_str = preg_replace("/\s+/u", " ", $str);
^^
See the PHP online demo.
The first thing to do is to read this explanation of how unicode can be treated in regex. Coming specifically to PHP, we need to first of all include the PCRE modifier 'u' for the engine to recognize UTF characters. So this would be:
$pattern = "/<our-pattern-here>/u";
The next thing is to note that in PHP unicode characters have the pattern \x{00A0} where 00A0 is hex representation for non-breaking space. So if we want to replace consecutive non-breaking spaces with a single space we would have:
$pattern = "/\x{00A0}+/u";
$new_str = preg_replace($pattern," ",$str);
And if we were to include other types of spaces mentioned in the wiki like:
\x{000D} carriage return
\x{000C} form feed
\x{0085} next line
Our pattern becomes:
$pattern = "/[\x{00A0}\x{000D}\x{000C}\x{0085}]+/u";
But this is really not great since the regex engine will take forever to find out all combinations of these characters. This is because the characters are included in square brackets [ ] and we have a + for one or more occurrences.
A better way to then get faster results is by replacing all occurrences of each of these characters by a normal space first. And then replacing multiple spaces with a single normal space. We remove the [ ]+ and instead separate the characters with the or operator | :
$pattern = "/\x{00A0}|\x{000D}|\x{000C}|\x{0085}/u";
$new_str = preg_replace($pattern," ",$str); // we have one-to-one replacement of character by a normal space, so 5 unicode chars give 5 normal spaces
$final_str = preg_replace("/\s+/", " ", $new_str); // multiple normal spaces now become single normal space
A pattern that matches all Unicode whitespaces is [\pZ\pC]. Here is a unit test to prove it.
If you're parsing user input in UTF-8 and need to normalize it, it's important to base your match on that list. So to answer your question that would be:
$new_str = preg_replace("/[\pZ\pC]+/u", " ", $str);
how I can use str_ireplace or other functions to remove any characters but not letters,numbers or symbols that are commonly used in HTML as : " ' ; : . - + =... etc. I also wants to remove /n, white spaces, tabs and other.
I need that text, comes from doing ("textContent"). innerHTML in IE10 and Chrome, which a php variable are the same size, regardless of which browser do it.Therefore I need the same encoding in both texts and characters that are rare or different are removed.
I try this, but it dont work for me:
$textForMatch=iconv(mb_detect_encoding($text, mb_detect_order(), true), "UTF-8", $text);
$textoForMatc = str_replace(array('\s', "\n", "\t", "\r"), '', $textoForMatch);
$text contains the result of the function ("textContent"). innerHTML, I want to delete characters as �é³..
The easiest option is to simply use preg_replace with a whitelist. I.e. use a pattern listing the things you want to keep, and replace anything not in that list:
$input = 'The quick brown 123 fox said "�é³". Man was I surprised';
$stripped = preg_replace('/[^-\w:";:+=\.\']/', '', $input);
$output = 'Thequickbrownfoxsaid"".ManwasIsurprised';
regex explanation
/ - start regex
[^ - Begin inverted character class, match NON-matching characters
- - litteral character
\w - Match word characters. Equivalent to A-Za-z0-9_
:";:+= - litteral characters
\. - escaped period (because a dot has meaning in a regex)
\' - escaped quote (because the string is in single quotes)
] - end character class
/ - end of regex
This will therefore remove anything that isn't words, numbers or the specific characters listed in the regex.
Sorry for the very basic question, but there's simply no easy way to search for a string like that nor here neither in Google or SymbolHound. Also haven't found an answer in PHP Manual (Pattern Syntax & preg_replace).
This code is inside a function that receives the $content and $length parameters.
What does that preg_replace serves for?
$the_string = preg_replace('#\s+#', ' ', $content);
$words = explode(' ', $the_string);
if( count($words) <= $length )
Also, would it be better to use str_word_count instead?
This pattern replaces successive space characters (note, not just spaces, but also line breaks or tabs) with a single, conventional space (' '). \s+ says "match a sequence, made up of one or more space characters".
The # signs are delimiters for the pattern. Probably more common is to see patterns delimited by forward slashes. (Actually you can do REGEX in PHP without delimiters but doing so has implications on how the pattern is handled, which is beyond the scope of this question/answer).
http://php.net/manual/en/regexp.reference.delimiters.php
Relying on spaces to find words in a string is generally not the best approach - we can use the \b word boundary marker instead.
$sentence = "Hello, there. How are you today? Hope you're OK!";
preg_match_all('/\b[\w-]+\b/', $sentence, $words);
That says: grab all substrings within the greater string that are comprised of only alphanumeric characters or hyphens, and which are encased by a word boundary.
$words is now an array of words used in the sentence.
# is delimiter
Often used delimiters are forward slashes (/), hash signs (#) and
tildes (~). The following are all examples of valid delimited
patterns.
$the_string = preg_replace('#\s+#', ' ', $content);
it will replace multiple space (\s) with single space
\s+ is used to match multiple spaces.
You are replacing them with a single space, using preg_replace('#\s+#', ' ', $content);
str_word_count might be suitable, but you might need to specify additional characters which count as words, or the function reports wrong values when using UTF-8 characters.
str_word_count($str, 1, characters_that_are_not_considered_word_boundaries);
EXAMPLE:
print_r(str_word_count('holóeóó what',1));
returns
Array ( [0] => hol [1] => e [2] => what )
I want to generate the string like SEO friendly URL. I want that multiple blank space to be eliminated, the single space to be replaced by a hyphen (-), then strtolower and no special chars should be allowed.
For that I am currently the code like this:
$string = htmlspecialchars("This Is The String");
$string = strtolower(str_replace(htmlspecialchars((' ', '-', $string)));
The above code will generate multiple hyphens. I want to eliminate that multiple space and replace it with only one space. In short, I am trying to achieve the SEO friendly URL like string. How do I do it?
You can use preg_replace to replace any sequence of whitespace chars with a dash...
$string = preg_replace('/\s+/', '-', $string);
The outer slashes are delimiters for the pattern - they just mark where the pattern starts and ends
\s matches any whitespace character
+ causes the previous element to match 1 or more times. By default, this is 'greedy' so it will eat up as many consecutive matches as it can.
See the manual page on PCRE syntax for more details
echo preg_replace('~(\s+)~', '-', $yourString);
What you want is "slugify" a string. Try a search on SO or google on "php slugify" or "php slug".
How to replace spaces and dashes when they appear together with only dash in PHP?
e.g below is my URL
http://kjd.case.150/1 BHK+Balcony- 700+ sqft. spacious apartmetn Bandra Wes
In this I want to replace all special characters with dash in PHP. In the URL there is already one dash after "balcony". If I replace the dash with a special character, then it becomes two dashes because there's already one dash in the URL and I want only 1 dash.
I'd say you may be want it other way. Not "spaces" but every non-alphanumeric character.
Because there can be other characters, disallowed in the URl (+ sign, for example, which is used as a space replacement)
So, to make a valid url from a free-form text
$url = preg_replace("![^a-z0-9]+!i", "-", $url);
If there could be max one space surrounding the hyphen you can use the answer by John. If there could be more than one space you can try using preg_replace:
$str = preg_replace('/\s*-\s*/','-',$str);
This would replace even a - not surrounded with any spaces with - !!
To make it a bit more efficient you could do:
$str = preg_replace('/\s+-\s*|\s*-\s+/','-',$str);
Now this would ensure a - has at least one space surrounding it while its being replaced.
This should do it for you
strtolower(str_replace(array(' ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));
Apply this regular expression /[^a-zA-Z0-9]/, '-' which will replace all non alphanumeric characters with -. Store it in a variable and again apply this regular expression /\-$/, '' which will escape the last character.
Its old tread but to help some one, Use this Function:
function urlSafeString($str)
{
$str = eregi_replace("[^a-z0-9\040]","",str_replace("-"," ",$str));
$str = eregi_replace("[\040]+","-",trim($str));
return $str;
}
it will return you a url safe string