Combining multiple regular expressions into one - php

I'm filtering all user input to remove the following characters:
http://www.w3.org/TR/unicode-xml/#Charlist ("not suitable characters for use with markup").
So, I have this two functions:
if (!function_exists("mb_trim")) {
function mb_trim($str)
{
return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $str);
}
}
function sanitize($str)
{
// Clones of grave and accent
$str = preg_replace("/[\x{0340}-\x{0341}]+/u", "", $str);
// Obsolete characters for Khmer
$str = preg_replace("/[\x{17A3}]+/u", "", $str);
$str = preg_replace("/[\x{17D3}]+/u", "", $str);
// Line and paragraph separator
$str = preg_replace("/[\x{2028}]+/u", "", $str);
$str = preg_replace("/[\x{2029}]+/u", "", $str);
// BIDI embedding controls (LRE, RLE, LRO, RLO, PDF)
$str = preg_replace("/[\x{202A}-\x{202E}]+/u", "", $str);
// Activate/Inhibit Symmetric swapping
$str = preg_replace("/[\x{206A}-\x{206B}]+/u", "", $str);
// Activate/Inhibit Arabic from shaping
$str = preg_replace("/[\x{206C}-\x{206D}]+/u", "", $str);
// Activate/Inhibit National digit shapes
$str = preg_replace("/[\x{206E}-\x{206F}]+/u", "", $str);
// Interlinear annotation characters
$str = preg_replace("/[\x{FFF9}-\x{FFFB}]+/u", "", $str);
// Byte Order Mark
$str = preg_replace("/[\x{FEFF}]+/u", "", $str);
// Object replacement character
$str = preg_replace("/[\x{FFFC}]+/u", "", $str);
// Scoping for Musical Notation
$str = preg_replace("/[\x{1D173}-\x{1D17A}]+/u", "", $str);
$str = mb_trim($str);
if (mb_check_encoding($str)) {
return $str;
} else {
return false;
}
}
I have not much knowledge with regular expresions, so, what I want to know is
Is the mb_trim function correct for trimming multi-byte strings?
Is it possible to join all regular expresions in the function
sanitize to do only one preg_replace?
Thanks

You can do with one preg_replace by combining them into a one character set like so:
$str = preg_replace("/[\x{0340}-\x{0341}\x{17A3}\x{17D3}\x{2028}-\x{2029}\x{202A}-\x{202E}\x{206A}-\x{206B}\x{206C}-\x{206D}\x{206E}-\x{206F}\x{FFF9}-\x{FFFB}\x{FEFF}\x{FFFC}\x{1D173}-\x{1D17A}]+/u", "", $str);

Related

Add hyperlinks to words in php

I have found this function on buildinternet.com.
function tag_it($text) {
$text = preg_replace("/:(\w+):/", '$1',$text);
return $text;
}
What it does is adding hyperlinks to words enclosed in ":" and the problem is that it works only with single words and it doesn`t work with words that has a single quote.
So if I do this,
$test = "one :word1:, :two words:, :this is a phrase:, this has a single quote :don't: or :don't forget:.";
echo tag_it($test);
only to the :word1: will be added a hyperlink, the rest will be ignored.
I don`t know too much php and I would appreciate if someone could make the function work with more than one word and with a single quote too.
Thank you!
Edit:
So I have tried the following to add a different link to words enclosed in "#"
function tag_it($text) {
$out = preg_replace_callback(
"/:([^\:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},
preg_replace_callback(
"/#([^\#]+)#/",
function($m1) {
$linkText1 = $m1[1];
$link1 = str_replace('"', '', $m1[1]);
$link1 = str_replace("'", "", $m1[1]);
$link1 = str_replace(" ", "_", $link1);
return ''.$linkText1.'';
},
$text
)
);
return $out;
}
$test = "one :word:, #two words#, :this is a phrase:, this has a single quote :don:'t or :don't forget:.";
echo tag_it($test);
and i get this
one word, two_words,_/" title="//www.example.com/blog/two_words/" title="two words" target="_blank">two words, " target="_blank">//www.example.com/blog/two_words/" title="two words" target="_blank">two words, this is a phrase, this has a single quote don't or don't forget:.
It seems to work for the 1st word enclosed in ":" and is trying to work with the words enclosed in "#" too but something is happening along the way and I can`t figure it out.
Any tip is really appreciated.
Thank you!
Change the crucial line in the function to the following:
$text = preg_replace("/:([^:]+):/", '$1', $text);
change this /:(\w+):/ to this /:([^:]+):/
Try this hope this simple one will help you out..
Regex: :([^\:]+):
:([^\:]+): it will match : then all till not : and then : in end
Try this code snippet here
<?php
ini_set('display_errors', 1);
$test = "one :word1:, :two words:, :this is a phrase:, this has a single quote :don't: or :don't forget:.";
echo tag_it($test);
function tag_it($text)
{
$text = preg_replace("/:([^\:]+):/", '$1', $text);
return $text;
}
I'll let you finish it off, above are all valid, but leave you with broken links, so building on them, I'd do something like:
function tag_it($text) {
$out = preg_replace_callback(
"/:([^:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', "", $m[1]);
$link = str_replace("'", "", $m[1]);
return ''.$linkText.'';
},
$text);
return $out;
}
You'll need to finish it off to replace spaces with - or _ or something but should be easy enough to work it out.
To answer to my "Edit:", I have figured out the problem.
Here is the full function
function tag_it($text) {
$out = preg_replace_callback(
"/:([^\:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$text
);
$out = preg_replace_callback(
"/#([^\#]+)#/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$out
);
$out = preg_replace_callback(
"/#([^\#]+)#/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$out
);
return $out;
}
$test = "one :word:, #two words#, #this is a phrase#, this has a single quote #don't# or :don't forget:.";
echo tag_it($test);

How can I pad each multibyte character / emoji with spaces around it in a string?

I'd like to pad each multibyte character with spaces on either side. I can strip them out just fine, but I'd like to leave them in and just pad them.
For example: 👉😀👈 to 👉 😀 👈.
Using underscores to represent spaces: 👉😀👈 to _👉__😀__👈_
Use this monsterous-already-cooked regex:
$regex = "[\\x{fe00}-\\x{fe0f}\\x{2712}\\x{2714}\\x{2716}\\x{271d}\\x{2721}\\x{2728}\\x{2733}\\x{2734}\\x{2744}\\x{2747}\\x{274c}\\x{274e}\\x{2753}-\\x{2755}\\x{2757}\\x{2763}\\x{2764}\\x{2795}-\\x{2797}\\x{27a1}\\x{27b0}\\x{27bf}\\x{2934}\\x{2935}\\x{2b05}-\\x{2b07}\\x{2b1b}\\x{2b1c}\\x{2b50}\\x{2b55}\\x{3030}\\x{303d}\\x{1f004}\\x{1f0cf}\\x{1f170}\\x{1f171}\\x{1f17e}\\x{1f17f}\\x{1f18e}\\x{1f191}-\\x{1f19a}\\x{1f201}\\x{1f202}\\x{1f21a}\\x{1f22f}\\x{1f232}-\\x{1f23a}\\x{1f250}\\x{1f251}\\x{1f300}-\\x{1f321}\\x{1f324}-\\x{1f393}\\x{1f396}\\x{1f397}\\x{1f399}-\\x{1f39b}\\x{1f39e}-\\x{1f3f0}\\x{1f3f3}-\\x{1f3f5}\\x{1f3f7}-\\x{1f4fd}\\x{1f4ff}-\\x{1f53d}\\x{1f549}-\\x{1f54e}\\x{1f550}-\\x{1f567}\\x{1f56f}\\x{1f570}\\x{1f573}-\\x{1f579}\\x{1f587}\\x{1f58a}-\\x{1f58d}\\x{1f590}\\x{1f595}\\x{1f596}\\x{1f5a5}\\x{1f5a8}\\x{1f5b1}\\x{1f5b2}\\x{1f5bc}\\x{1f5c2}-\\x{1f5c4}\\x{1f5d1}-\\x{1f5d3}\\x{1f5dc}-\\x{1f5de}\\x{1f5e1}\\x{1f5e3}\\x{1f5ef}\\x{1f5f3}\\x{1f5fa}-\\x{1f64f}\\x{1f680}-\\x{1f6c5}\\x{1f6cb}-\\x{1f6d0}\\x{1f6e0}-\\x{1f6e5}\\x{1f6e9}\\x{1f6eb}\\x{1f6ec}\\x{1f6f0}\\x{1f6f3}\\x{1f910}-\\x{1f918}\\x{1f980}-\\x{1f984}\\x{1f9c0}\\x{3297}\\x{3299}\\x{a9}\\x{ae}\\x{203c}\\x{2049}\\x{2122}\\x{2139}\\x{2194}-\\x{2199}\\x{21a9}\\x{21aa}\\x{231a}\\x{231b}\\x{2328}\\x{2388}\\x{23cf}\\x{23e9}-\\x{23f3}\\x{23f8}-\\x{23fa}\\x{24c2}\\x{25aa}\\x{25ab}\\x{25b6}\\x{25c0}\\x{25fb}-\\x{25fe}\\x{2600}-\\x{2604}\\x{260e}\\x{2611}\\x{2614}\\x{2615}\\x{2618}\\x{261d}\\x{2620}\\x{2622}\\x{2623}\\x{2626}\\x{262a}\\x{262e}\\x{262f}\\x{2638}-\\x{263a}\\x{2648}-\\x{2653}\\x{2660}\\x{2663}\\x{2665}\\x{2666}\\x{2668}\\x{267b}\\x{267f}\\x{2692}-\\x{2694}\\x{2696}\\x{2697}\\x{2699}\\x{269b}\\x{269c}\\x{26a0}\\x{26a1}\\x{26aa}\\x{26ab}\\x{26b0}\\x{26b1}\\x{26bd}\\x{26be}\\x{26c4}\\x{26c5}\\x{26c8}\\x{26ce}\\x{26cf}\\x{26d1}\\x{26d3}\\x{26d4}\\x{26e9}\\x{26ea}\\x{26f0}-\\x{26f5}\\x{26f7}-\\x{26fa}\\x{26fd}\\x{2702}\\x{2705}\\x{2708}-\\x{270d}\\x{270f}]|\\x{23}\\x{20e3}|\\x{2a}\\x{20e3}|\\x{30}\\x{20e3}|\\x{31}\\x{20e3}|\\x{32}\\x{20e3}|\\x{33}\\x{20e3}|\\x{34}\\x{20e3}|\\x{35}\\x{20e3}|\\x{36}\\x{20e3}|\\x{37}\\x{20e3}|\\x{38}\\x{20e3}|\\x{39}\\x{20e3}|\\x{1f1e6}[\\x{1f1e8}-\\x{1f1ec}\\x{1f1ee}\\x{1f1f1}\\x{1f1f2}\\x{1f1f4}\\x{1f1f6}-\\x{1f1fa}\\x{1f1fc}\\x{1f1fd}\\x{1f1ff}]|\\x{1f1e7}[\\x{1f1e6}\\x{1f1e7}\\x{1f1e9}-\\x{1f1ef}\\x{1f1f1}-\\x{1f1f4}\\x{1f1f6}-\\x{1f1f9}\\x{1f1fb}\\x{1f1fc}\\x{1f1fe}\\x{1f1ff}]|\\x{1f1e8}[\\x{1f1e6}\\x{1f1e8}\\x{1f1e9}\\x{1f1eb}-\\x{1f1ee}\\x{1f1f0}-\\x{1f1f5}\\x{1f1f7}\\x{1f1fa}-\\x{1f1ff}]|\\x{1f1e9}[\\x{1f1ea}\\x{1f1ec}\\x{1f1ef}\\x{1f1f0}\\x{1f1f2}\\x{1f1f4}\\x{1f1ff}]|\\x{1f1ea}[\\x{1f1e6}\\x{1f1e8}\\x{1f1ea}\\x{1f1ec}\\x{1f1ed}\\x{1f1f7}-\\x{1f1fa}]|\\x{1f1eb}[\\x{1f1ee}-\\x{1f1f0}\\x{1f1f2}\\x{1f1f4}\\x{1f1f7}]|\\x{1f1ec}[\\x{1f1e6}\\x{1f1e7}\\x{1f1e9}-\\x{1f1ee}\\x{1f1f1}-\\x{1f1f3}\\x{1f1f5}-\\x{1f1fa}\\x{1f1fc}\\x{1f1fe}]|\\x{1f1ed}[\\x{1f1f0}\\x{1f1f2}\\x{1f1f3}\\x{1f1f7}\\x{1f1f9}\\x{1f1fa}]|\\x{1f1ee}[\\x{1f1e8}-\\x{1f1ea}\\x{1f1f1}-\\x{1f1f4}\\x{1f1f6}-\\x{1f1f9}]|\\x{1f1ef}[\\x{1f1ea}\\x{1f1f2}\\x{1f1f4}\\x{1f1f5}]|\\x{1f1f0}[\\x{1f1ea}\\x{1f1ec}-\\x{1f1ee}\\x{1f1f2}\\x{1f1f3}\\x{1f1f5}\\x{1f1f7}\\x{1f1fc}\\x{1f1fe}\\x{1f1ff}]|\\x{1f1f1}[\\x{1f1e6}-\\x{1f1e8}\\x{1f1ee}\\x{1f1f0}\\x{1f1f7}-\\x{1f1fb}\\x{1f1fe}]|\\x{1f1f2}[\\x{1f1e6}\\x{1f1e8}-\\x{1f1ed}\\x{1f1f0}-\\x{1f1ff}]|\\x{1f1f3}[\\x{1f1e6}\\x{1f1e8}\\x{1f1ea}-\\x{1f1ec}\\x{1f1ee}\\x{1f1f1}\\x{1f1f4}\\x{1f1f5}\\x{1f1f7}\\x{1f1fa}\\x{1f1ff}]|\\x{1f1f4}\\x{1f1f2}|\\x{1f1f5}[\\x{1f1e6}\\x{1f1ea}-\\x{1f1ed}\\x{1f1f0}-\\x{1f1f3}\\x{1f1f7}-\\x{1f1f9}\\x{1f1fc}\\x{1f1fe}]|\\x{1f1f6}\\x{1f1e6}|\\x{1f1f7}[\\x{1f1ea}\\x{1f1f4}\\x{1f1f8}\\x{1f1fa}\\x{1f1fc}]|\\x{1f1f8}[\\x{1f1e6}-\\x{1f1ea}\\x{1f1ec}-\\x{1f1f4}\\x{1f1f7}-\\x{1f1f9}\\x{1f1fb}\\x{1f1fd}-\\x{1f1ff}]|\\x{1f1f9}[\\x{1f1e6}\\x{1f1e8}\\x{1f1e9}\\x{1f1eb}-\\x{1f1ed}\\x{1f1ef}-\\x{1f1f4}\\x{1f1f7}\\x{1f1f9}\\x{1f1fb}\\x{1f1fc}\\x{1f1ff}]|\\x{1f1fa}[\\x{1f1e6}\\x{1f1ec}\\x{1f1f2}\\x{1f1f8}\\x{1f1fe}\\x{1f1ff}]|\\x{1f1fb}[\\x{1f1e6}\\x{1f1e8}\\x{1f1ea}\\x{1f1ec}\\x{1f1ee}\\x{1f1f3}\\x{1f1fa}]|\\x{1f1fc}[\\x{1f1eb}\\x{1f1f8}]|\\x{1f1fd}\\x{1f1f0}|\\x{1f1fe}[\\x{1f1ea}\\x{1f1f9}]|\\x{1f1ff}[\\x{1f1e6}\\x{1f1f2}\\x{1f1fc}]";
Inside a preg_replace_callback():
var_dump(preg_replace_callback("#$regex#u", function($match) {
return $match[0]." ";
}, '👉😀👈'));
Outputs:
string(18) "👉 😀 👈 "
Live demo
I found this function that someone had added in the PHP docs that splits a multibyte string into an array of characters (like str_split) and modified it.
function addSpaces($string) {
$strlen = mb_strlen($string);
$new_string = '';
while ($strlen) {
$char = mb_substr($string,0,1,"UTF-8");
if (strlen($char) > 1) {
$new_string .= " $char ";
} else {
$new_string .= $char;
}
$string = mb_substr($string,1,$strlen,"UTF-8");
$strlen = mb_strlen($string);
}
return $new_string;
}
This question has other ways to do that split that could be similarly modified. The modification is, if strlen of one of the split characters is greater than 1, then it's multibyte, so add the spaces.
Simple regex replace could work as well...
mb_regex_encoding("UTF-8");
echo mb_ereg_replace(
'([^\p{L}\s])',
' \\1 ',
'text 👉😀👈 other text 👉😀👈'
);
outputs: text 👉 😀 👈 other text 👉 😀 👈
function pad_emojis($string) {
$default_encoding = mb_regex_encoding();
mb_regex_encoding("UTF-8");
$string = mb_ereg_replace('([^\p{L}\s])', ' \\1 ', $string);
mb_regex_encoding($default_encoding);
return $string;
}

Regular expression for finding multiple patterns from a given string

I am using regular expression for getting multiple patterns from a given string.
Here, I will explain you clearly.
$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag);
The above is my code.
Here, i am finding the space in a word and replacing the space with the special character what ever i need, right??
Now, I need a regular expression that gives me patterns like
about_us, about-us, aboutus as output if i give about us as input.
Is this possible to do.
Please help me in that.
Thanks in advance!
And finally, my answer is
$string = "contact_us";
$a = array('-','_',' ');
foreach($a as $b){
if(strpos($string,$b)){
$separators = array('-','_','',' ');
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/".$b."/", $sep, $string);
}
print_r($outputs);
}
}
exit;
You need to do a loop to handle multiple possible outputs :
$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
You can try without regex:
$string = 'about us';
$specialChar = '-'; // or any other
$newtag = implode($specialChar, explode(' ', $string));
If you put special characters into an array:
$specialChars = array('_', '-', '');
$newtags = array();
foreach ($specialChars as $specialChar) {
$newtags[] = implode($specialChar, explode(' ', $string));
}
Also you can use just str_replace()
foreach ($specialChars as $specialChar) {
$newtags[] = str_replace(' ', $specialChar, $string);
}
Not knowing exactly what you want to do I expect that you might want to replace any occurrence of a non-word (1 or more times) with a single dash.
e.g.
preg_replace('/\W+/', '-', $string);
If you just want to replace the space, use \s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
I am not sure that regexes are the good tool for that. However you can simply define this kind of function:
function rep($str) {
return array( strtr($str, ' ', '_'),
strtr($str, ' ', '-'),
str_replace(' ', '', $str) );
}
$result = rep('about us');
print_r($result);
Matches any character that is not a word character
$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);
in case its just that... you would get problems if it's a longer string :)

Remove non-ascii characters from string

I'm getting strange characters when pulling data from a website:
Â
How can I remove anything that isn't a non-extended ASCII character?
A more appropriate question can be found here:
PHP - replace all non-alphanumeric chars for all languages supported
A regex replace would be the best option. Using $str as an example string and matching it using :print:, which is a POSIX Character Class:
$str = 'aAÂ';
$str = preg_replace('/[[:^print:]]/', '', $str); // should be aA
What :print: does is look for all printable characters. The reverse, :^print:, looks for all non-printable characters. Any characters that are not part of the current character set will be removed.
Note: Before using this method, you must ensure that your current character set is ASCII. POSIX Character Classes support both ASCII and Unicode and will match only according to the current character set. As of PHP 5.6, the default charset is UTF-8.
You want only ASCII printable characters?
use this:
<?php
header('Content-Type: text/html; charset=UTF-8');
$str = "abqwrešđčžsff";
$res = preg_replace('/[^\x20-\x7E]/','', $str);
echo "($str)($res)";
Or even better, convert your input to utf8 and use phputf8 lib to translate 'not normal' characters into their ascii representation:
require_once('libs/utf8/utf8.php');
require_once('libs/utf8/utils/bad.php');
require_once('libs/utf8/utils/validation.php');
require_once('libs/utf8_to_ascii/utf8_to_ascii.php');
if(!utf8_is_valid($str))
{
$str=utf8_bad_strip($str);
}
$str = utf8_to_ascii($str, '' );
$clearstring=filter_var($rawstring, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
UPDATE:
FILTER_SANITIZE_STRING is deprecated since PHP 8.1
https://www.php.net/manual/en/migration81.deprecated.php#migration81.deprecated.filter
Kind of related, we had a web application that had to send data to a legacy system that could only deal with the first 128 characters of the ASCII character set.
Solution we had to use was something that would "translate" as many characters as possible into close-matching ASCII equivalents, but leave anything that could not be translated alone.
Normally I would do something like this:
<?php
// transliterate
if (function_exists('iconv')) {
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
?>
... but that replaces everything that can't be translated into a question mark (?).
So we ended up doing the following. Check at the end of this function for (commented out) php regex that just strips out non-ASCII characters.
<?php
public function cleanNonAsciiCharactersInString($orig_text) {
$text = $orig_text;
// Single letters
$text = preg_replace("/[∂άαáàâãªä]/u", "a", $text);
$text = preg_replace("/[∆лДΛдАÁÀÂÃÄ]/u", "A", $text);
$text = preg_replace("/[ЂЪЬБъь]/u", "b", $text);
$text = preg_replace("/[βвВ]/u", "B", $text);
$text = preg_replace("/[çς©с]/u", "c", $text);
$text = preg_replace("/[ÇС]/u", "C", $text);
$text = preg_replace("/[δ]/u", "d", $text);
$text = preg_replace("/[éèêëέëèεе℮ёєэЭ]/u", "e", $text);
$text = preg_replace("/[ÉÈÊË€ξЄ€Е∑]/u", "E", $text);
$text = preg_replace("/[₣]/u", "F", $text);
$text = preg_replace("/[НнЊњ]/u", "H", $text);
$text = preg_replace("/[ђћЋ]/u", "h", $text);
$text = preg_replace("/[ÍÌÎÏ]/u", "I", $text);
$text = preg_replace("/[íìîïιίϊі]/u", "i", $text);
$text = preg_replace("/[Јј]/u", "j", $text);
$text = preg_replace("/[ΚЌК]/u", 'K', $text);
$text = preg_replace("/[ќк]/u", 'k', $text);
$text = preg_replace("/[ℓ∟]/u", 'l', $text);
$text = preg_replace("/[Мм]/u", "M", $text);
$text = preg_replace("/[ñηήηπⁿ]/u", "n", $text);
$text = preg_replace("/[Ñ∏пПИЙийΝЛ]/u", "N", $text);
$text = preg_replace("/[óòôõºöοФσόо]/u", "o", $text);
$text = preg_replace("/[ÓÒÔÕÖθΩθОΩ]/u", "O", $text);
$text = preg_replace("/[ρφрРф]/u", "p", $text);
$text = preg_replace("/[®яЯ]/u", "R", $text);
$text = preg_replace("/[ГЃгѓ]/u", "r", $text);
$text = preg_replace("/[Ѕ]/u", "S", $text);
$text = preg_replace("/[ѕ]/u", "s", $text);
$text = preg_replace("/[Тт]/u", "T", $text);
$text = preg_replace("/[τ†‡]/u", "t", $text);
$text = preg_replace("/[úùûüџμΰµυϋύ]/u", "u", $text);
$text = preg_replace("/[√]/u", "v", $text);
$text = preg_replace("/[ÚÙÛÜЏЦц]/u", "U", $text);
$text = preg_replace("/[Ψψωώẅẃẁщш]/u", "w", $text);
$text = preg_replace("/[ẀẄẂШЩ]/u", "W", $text);
$text = preg_replace("/[ΧχЖХж]/u", "x", $text);
$text = preg_replace("/[ỲΫ¥]/u", "Y", $text);
$text = preg_replace("/[ỳγўЎУуч]/u", "y", $text);
$text = preg_replace("/[ζ]/u", "Z", $text);
// Punctuation
$text = preg_replace("/[‚‚]/u", ",", $text);
$text = preg_replace("/[`‛′’‘]/u", "'", $text);
$text = preg_replace("/[″“”«»„]/u", '"', $text);
$text = preg_replace("/[—–―−–‾⌐─↔→←]/u", '-', $text);
$text = preg_replace("/[ ]/u", ' ', $text);
$text = str_replace("…", "...", $text);
$text = str_replace("≠", "!=", $text);
$text = str_replace("≤", "<=", $text);
$text = str_replace("≥", ">=", $text);
$text = preg_replace("/[‗≈≡]/u", "=", $text);
// Exciting combinations
$text = str_replace("ыЫ", "bl", $text);
$text = str_replace("℅", "c/o", $text);
$text = str_replace("₧", "Pts", $text);
$text = str_replace("™", "tm", $text);
$text = str_replace("№", "No", $text);
$text = str_replace("Ч", "4", $text);
$text = str_replace("‰", "%", $text);
$text = preg_replace("/[∙•]/u", "*", $text);
$text = str_replace("‹", "<", $text);
$text = str_replace("›", ">", $text);
$text = str_replace("‼", "!!", $text);
$text = str_replace("⁄", "/", $text);
$text = str_replace("∕", "/", $text);
$text = str_replace("⅞", "7/8", $text);
$text = str_replace("⅝", "5/8", $text);
$text = str_replace("⅜", "3/8", $text);
$text = str_replace("⅛", "1/8", $text);
$text = preg_replace("/[‰]/u", "%", $text);
$text = preg_replace("/[Љљ]/u", "Ab", $text);
$text = preg_replace("/[Юю]/u", "IO", $text);
$text = preg_replace("/[fifl]/u", "fi", $text);
$text = preg_replace("/[зЗ]/u", "3", $text);
$text = str_replace("£", "(pounds)", $text);
$text = str_replace("₤", "(lira)", $text);
$text = preg_replace("/[‰]/u", "%", $text);
$text = preg_replace("/[↨↕↓↑│]/u", "|", $text);
$text = preg_replace("/[∞∩∫⌂⌠⌡]/u", "", $text);
//2) Translation CP1252.
$trans = get_html_translation_table(HTML_ENTITIES);
$trans['f'] = 'ƒ'; // Latin Small Letter F With Hook
$trans['-'] = array(
'…', // Horizontal Ellipsis
'˜', // Small Tilde
'–' // Dash
);
$trans["+"] = '†'; // Dagger
$trans['#'] = '‡'; // Double Dagger
$trans['M'] = '‰'; // Per Mille Sign
$trans['S'] = 'Š'; // Latin Capital Letter S With Caron
$trans['OE'] = 'Œ'; // Latin Capital Ligature OE
$trans["'"] = array(
'‘', // Left Single Quotation Mark
'’', // Right Single Quotation Mark
'›', // Single Right-Pointing Angle Quotation Mark
'‚', // Single Low-9 Quotation Mark
'ˆ', // Modifier Letter Circumflex Accent
'‹' // Single Left-Pointing Angle Quotation Mark
);
$trans['"'] = array(
'“', // Left Double Quotation Mark
'”', // Right Double Quotation Mark
'„', // Double Low-9 Quotation Mark
);
$trans['*'] = '•'; // Bullet
$trans['n'] = '–'; // En Dash
$trans['m'] = '—'; // Em Dash
$trans['tm'] = '™'; // Trade Mark Sign
$trans['s'] = 'š'; // Latin Small Letter S With Caron
$trans['oe'] = 'œ'; // Latin Small Ligature OE
$trans['Y'] = 'Ÿ'; // Latin Capital Letter Y With Diaeresis
$trans['euro'] = '€'; // euro currency symbol
ksort($trans);
foreach ($trans as $k => $v) {
$text = str_replace($v, $k, $text);
}
// 3) remove <p>, <br/> ...
$text = strip_tags($text);
// 4) & => & " => '
$text = html_entity_decode($text);
// transliterate
// if (function_exists('iconv')) {
// $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// }
// remove non ascii characters
// $text = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $text);
return $text;
}
?>
I also think that the best solution might be to use a regular expression.
Here's my suggestion:
function convert_to_normal_text($text) {
$normal_characters = "a-zA-Z0-9\s`~!##$%^&*()_+-={}|:;<>?,.\/\"\'\\\[\]";
$normal_text = preg_replace("/[^$normal_characters]/", '', $text);
return $normal_text;
}
Then you can use it like this:
$before = 'Some "normal characters": Abc123!+, some ASCII characters: ABC+ŤĎ and some non-ASCII characters: Ąąśćł.';
$after = convert_to_normal_text($before);
echo $after;
Displays:
Some "normal characters": Abc123!+, some ASCII characters: ABC+ and some non-ASCII characters: .
I just had to add the header
header('Content-Type: text/html; charset=UTF-8');
This should be pretty straight forwards and no need for iconv function:
// Remove all characters that are not the separator, a-z, 0-9, or whitespace
$string = preg_replace('![^'.preg_quote('-').'a-z0-_9\s]+!', '', strtolower($string));
// Replace all separator characters and whitespace by a single separator
$string = preg_replace('!['.preg_quote('-').'\s]+!u', '-', $string);
My problem is solved
$text = 'Châu Thái Nhân 12/09/2022';
echo preg_replace('/[\x00-\x1F\x7F]/', '', $text);
//Châu Thái Nhân 12/09/2022
I think the best way to do something like this is by using ord() command. This way you will be able to keep characters written in any language. Just remember to first test your text's ord results. This will not work on unicode.
$name="βγδεζηΘKgfgebhjrf!##$%^&";
//this function will clear all non greek and english characters on greek-iso charset
function replace_characters($string)
{
$str_length=strlen($string);
for ($x=0;$x<$str_length;$x++)
{
$character=$string[$x];
if ((ord($character)>64 && ord($character)<91) || (ord($character)>96 && ord($character)<123) || (ord($character)>192 && ord($character)<210) || (ord($character)>210 && ord($character)<218) || (ord($character)>219 && ord($character)<250) || ord($character)==252 || ord($character)==254)
{
$new_string=$new_string.$character;
}
}
return $new_string;
}
//end function
$name=replace_characters($name);
echo $name;

PHP - a function to "sanitize" a string

is there any PHP function available that replaces spaces and underscores from a string with dashes?
Like:
Some Word
Some_Word
Some___Word
Some Word
Some ) # $ ^ Word
=> some-word
basically, the sanitized string should only contain a-z characters, numbers (0-9), and dashes (-).
This should produce the desired result:
$someword = strtolower(preg_replace("/[^a-z]+/i", "-", $theword));
<?php
function sanitize($s) {
// This RegEx removes any group of non-alphanumeric or dash
// character and replaces it/them with a dash
return strtolower(preg_replace('/[^a-z0-9-]+/i', '-', $s));
}
echo sanitize('Some Word') . "\n";
echo sanitize('Some_Word') . "\n";
echo sanitize('Some___Word') . "\n";
echo sanitize('Some Word') . "\n";
echo sanitize('Some ) # $ ^ Word') . "\n";
Output:
Some-Word
Some-Word
Some-Word
Some-Word
Some-Word
You might like to try preg_replace:
http://php.net/manual/en/function.preg-replace.php
Example from this page:
<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
//April1,2003
?>
You might like to try a search for "search friendly URLs with PHP" as there is quite a bit of documentation, example:
function friendlyURL($string){
$string = preg_replace("`\[.*\]`U","",$string);
$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');
$string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string );
$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);
return strtolower(trim($string, '-'));
}
and usage:
$myFriendlyURL = friendlyURL("Barca rejects FIFA statement on Olympics row");
echo $myFriendlyURL; // will echo barca-rejects-fifa-statement-on-olympics-row
Source: http://htmlblog.net/seo-friendly-url-in-php/
I found a few interesting solutions throughout the web.. note none of this is my code. Simply copied here in hopes of helping you build a custom function for your own app.
This has been copied from Chyrp. Should work well for your needs!
/**
* Function: sanitize
* Returns a sanitized string, typically for URLs.
*
* Parameters:
* $string - The string to sanitize.
* $force_lowercase - Force the string to lowercase?
* $anal - If set to *true*, will remove all non-alphanumeric characters.
*/
function sanitize($string, $force_lowercase = true, $anal = false) {
$strip = array("~", "`", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
"}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
"—", "–", ",", "<", ".", ">", "/", "?");
$clean = trim(str_replace($strip, "", strip_tags($string)));
$clean = preg_replace('/\s+/', "-", $clean);
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
EDIT:
Even easier function I found! Just a few lines of code, fairly self-explanitory.
function slug($z){
$z = strtolower($z);
$z = preg_replace('/[^a-z0-9 -]+/', '', $z);
$z = str_replace(' ', '-', $z);
return trim($z, '-');
}
Not sure why #Dagon chose to leave a comment instead of an answer, but here's an expansion of his answer.
php's preg_replace function allows you to replace anything with anything else.
Here's an example for your case:
$input = "a word 435 (*^(*& HaHa";
$dashesOnly = preg_replace("#[^-a-zA-Z0-9]+#", "-", $input);
print $dashesOnly; // prints a-word-435-HaHa;
You can think of writing this piece of code with the help of regular expressions.
But I dont see any available functions which help you directly replace the " " with "-"

Categories