I want to block to use space. Where must i edit and what to write?
$k = "".$post['dname'.$i]."";
$name = preg_replace("/[^a-zA-Z0-9_-\s]/", "", $k);
$database->setVillageName($database->RemoveXSS($varray[$i]['wref']),$name);
If you only want to allow one space in your string, then you could use the or operator in a regex.
$str = 'some name';
if(preg_match('/^([\w]+|[\w]+ [\w]+)$/', $str, $matches))
{
echo 'success';
}
else
{
echo 'fail';
}
This code will succeed when there are 0 or 1 spaces in the string. Otherwise it will fail if it has more spaces.
You can play with the code: http://codepad.viper-7.com/yTtWz1
A preg_replace would of course be similar:
preg_replace('/^([\w]+|[\w]+ [\w]+)$/', "", $str)
Just remove the \s from the character class:
$name = preg_replace("/[^a-zA-Z0-9_-]/", "", $k);
or (shorter):
$name = preg_replace("/[^\w-]/", "", $k);
Edit
$k = "".$post['dname'.$i]."";
$name = preg_replace("/[^\w\s-]/", "", $k);
if (preg_match('/^\s+$/', $name) {
// error : $name mustn't be all spaces
// do appropriate stuff
}
$database->setVillageName($database->RemoveXSS($varray[$i]['wref']),$name);
Related
I am using a WordPress plugin named Acronyms (https://wordpress.org/plugins/acronyms/). This plugin replaces acronyms with their description. It uses a PHP PREG_REPLACE function.
The issue is that it replaces the acronyms contained in a <pre> tag, which I use to present a source code.
Could you modify this expression so that it won't replace acronyms contained inside <pre> tags (not only directly, but in any moment)? Is it possible?
The PHP code is:
$text = preg_replace(
"|(?!<[^<>]*?)(?<![?.&])\b$acronym\b(?!:)(?![^<>]*?>)|msU"
, "<acronym title=\"$fulltext\">$acronym</acronym>"
, $text
);
You can use a PCRE SKIP/FAIL regex trick (also works in PHP) to tell the regex engine to only match something if it is not inside some delimiters:
(?s)<pre[^<]*>.*?<\/pre>(*SKIP)(*F)|\b$acronym\b
This means: skip all substrings starting with <pre> and ending with </pre>, and only then match $acronym as a whole word.
See demo on regex101.com
Here is a sample PHP demo:
<?php
$acronym = "ASCII";
$fulltext = "American Standard Code for Information Interchange";
$re = "/(?s)<pre[^<]*>.*?<\\/pre>(*SKIP)(*F)|\\b$acronym\\b/";
$str = "<pre>ASCII\nSometext\nMoretext</pre>More text \nASCII\nMore text<pre>More\nlines\nASCII\nlines</pre>";
$subst = "<acronym title=\"$fulltext\">$acronym</acronym>";
$result = preg_replace($re, $subst, $str);
echo $result;
Output:
<pre>ASCII</pre><acronym title="American Standard Code for Information Interchange">ASCII</acronym><pre>ASCII</pre>
It is also possible to use preg_split and keep the code block as a group, only replace the non-code block part then combine it back as a complete string:
function replace($s) {
return str_replace('"', '"', $s); // do something with `$s`
}
$text = 'Your text goes here...';
$parts = preg_split('#(<\/?[-:\w]+(?:\s[^<>]+?)?>)#', $text, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$text = "";
$x = 0;
foreach ($parts as $v) {
if (trim($v) === "") {
$text .= $v;
continue;
}
if ($v[0] === '<' && substr($v, -1) === '>') {
if (preg_match('#^<(\/)?(?:code|pre)(?:\s[^<>]+?)?>$#', $v, $m)) {
$x = isset($m[1]) && $m[1] === '/' ? 0 : 1;
}
$text .= $v; // this is a HTML tag…
} else {
$text .= !$x ? replace($v) : $v; // process or skip…
}
}
return $text;
Taken from here.
Objective: strings with ' should match the string without it.
Example:
$first_string = "alex ern o'brian";
$second_string = "alex-ern o brian";
$pattern = array("/(-|\.| )/", "/(')/");
$replace = array(' ', '(\s|)');
$first_string = preg_replace($pattern, $replace, $first_string);
$second_string = preg_replace($pattern, $replace, $second_string);
$first_string_split = preg_split("/(-|\.| )/", $first_string);
$first_string_split[] = $first_string;
$second_string_split = preg_split("/(-|\.| )/", $second_string);
$second_string_split[] = $second_string;
$first_string = array_slice($first_string_split, -1)[0];
$second_string = array_slice($second_string_split, -1)[0];
if(in_array($first_string, $second_string_split) || in_array($second_string, $first_string_split))
{
echo 'true';
} else {
echo 'false';
}
I think you are expecting this.
Solution 1: Try this code snippet here
Regex: (\s|) this will match either space or null.
<?php
ini_set('display_errors', 1);
$string = "o'brian";
$string=str_replace("'", "(\s|)",$string);
$list = array("o'neal", "o brian", "obrian");
$result=array();
foreach($list as $value)
{
if(preg_match("/$string/", $value))
{
$result[]=$value;
}
}
print_r($result);
Solution 2:
Regex: [a-z]+ will match character from a to z.
$string1="o brian";
$string2="obrian";
if(preg_match("/".implode(" ", $matches[0])."/", $string1))
{
echo "matched";
}
if( preg_match("/".implode("", $matches[0])."/", $string2))
{
echo "matched";
}
I'm not sure if I got your question right, but this should do it:
(?<=\w)'(?=\w)
It matches every ' character, which is followed and preceded by a word character. The word character \w is equal to [a-zA-Z0-9_].
Here is a live example to test the regex
Here is a live PHP example
i want to block or remove all unwanted characters from from my site
characters like ᾄҭᾄ
or нєℓℓσ
ĤĔĹĹŐ
etc..
my code now is
class badWordsC
{
public function check($text)
{
$badwords = 'com|net|org|info|.name|.biz|.me|.tv|.tel|.mobi|.asia|.uk|.eu|.us|.in|.tk|.cc|.ws|.bz|.mn|.co|.tw|.vn|.es|.pw|.club|.ca|.cn|.email|.photography|.photos|.tips|.solutions|.center|.gallery|.kitchen|.land|.technology|.today|.academy|.computer|.shoes|.careers|.domains|.coffee|.link|.guru|.estate|.company|.bike|.clothing|.holdings|.plumbing|.singles|.ventures|.camera|.equipment|.graphics|.lighting|.construction|.contractors|.directory|.diamonds|.enterprises|.voyage|.recipes|.gift|.site|.ly|.gq|.cf|.ga|.ml|.tk|in|rb2';
$badwords .= 'type|ingoogle';
$badwords = explode('|', $badwords);
$goodwords = 'youtube.com|prntscr.com|az545221.vo.msecnd.net';
$goodwords .= 'wink|crying|fingerscrossed|blushing|wondering|inlove|evilgrin|yawning|puking|in';
$goodwords = explode('|', $goodwords);
$text = str_replace($goodwords, '', $text);
$text = trim(preg_replace('/\s\s+/', '', $text));
$text = preg_replace('/\P{L}+/u', '', $text);
foreach ($badwords as $word)
{
if (strpos($text, $word) !== false || strpos($text, strtoupper($word)) !== false)
{
return false;
}
}
$text = preg_replace("/[a-zA-Z0-9]/", '', $text);
$text = preg_replace(array('/)/','/(/','/;/','/-/','/+/','/لأ/','/لإ/','/لا/','/إ/','/أ/', '/ا/', '/ض/', '/ص/', '/ث/', '/ق/', '/ف/', '/غ/', '/ع/', '/ه/', '/خ/', '/ح/', '/ج/', '/د/', '/ش/', '/س/', '/ي/', '/ب/', '/ل/', '/ت/', '/ن/', '/م/', '/ك/', '/ط/', '/ئ/', '/ء/', '/ؤ/', '/ر/', '/ى/', '/ة/', '/و/', '/ز/', '/ظ/', '/ذ/', '/ـ/'), '', $text);
if($text != '')
{
return false;
}
return true;
}
}
its working but not bloking or removing characters like н Ĕ Ő
any idea ?
The u modifier you will need to use you also need to expand your character class to include the non-ascii characters.
I'd use:
/[[:alnum:]]/u
Regex Demo: https://regex101.com/r/iS1yZ2/2
That is a posix bracket, you can see more of those here, www.regular-expressions.info/posixbrackets.html.
Also in your second expression the + needs to be escaped (or put in a character class, there are some symbols putting in a character won't fix -, ], ^) because that is a quantifier. There is a PHP function that will escape special characters, preg_quote.
I am using a WordPress plugin named Acronyms (https://wordpress.org/plugins/acronyms/). This plugin replaces acronyms with their description. It uses a PHP PREG_REPLACE function.
The issue is that it replaces the acronyms contained in a <pre> tag, which I use to present a source code.
Could you modify this expression so that it won't replace acronyms contained inside <pre> tags (not only directly, but in any moment)? Is it possible?
The PHP code is:
$text = preg_replace(
"|(?!<[^<>]*?)(?<![?.&])\b$acronym\b(?!:)(?![^<>]*?>)|msU"
, "<acronym title=\"$fulltext\">$acronym</acronym>"
, $text
);
You can use a PCRE SKIP/FAIL regex trick (also works in PHP) to tell the regex engine to only match something if it is not inside some delimiters:
(?s)<pre[^<]*>.*?<\/pre>(*SKIP)(*F)|\b$acronym\b
This means: skip all substrings starting with <pre> and ending with </pre>, and only then match $acronym as a whole word.
See demo on regex101.com
Here is a sample PHP demo:
<?php
$acronym = "ASCII";
$fulltext = "American Standard Code for Information Interchange";
$re = "/(?s)<pre[^<]*>.*?<\\/pre>(*SKIP)(*F)|\\b$acronym\\b/";
$str = "<pre>ASCII\nSometext\nMoretext</pre>More text \nASCII\nMore text<pre>More\nlines\nASCII\nlines</pre>";
$subst = "<acronym title=\"$fulltext\">$acronym</acronym>";
$result = preg_replace($re, $subst, $str);
echo $result;
Output:
<pre>ASCII</pre><acronym title="American Standard Code for Information Interchange">ASCII</acronym><pre>ASCII</pre>
It is also possible to use preg_split and keep the code block as a group, only replace the non-code block part then combine it back as a complete string:
function replace($s) {
return str_replace('"', '"', $s); // do something with `$s`
}
$text = 'Your text goes here...';
$parts = preg_split('#(<\/?[-:\w]+(?:\s[^<>]+?)?>)#', $text, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$text = "";
$x = 0;
foreach ($parts as $v) {
if (trim($v) === "") {
$text .= $v;
continue;
}
if ($v[0] === '<' && substr($v, -1) === '>') {
if (preg_match('#^<(\/)?(?:code|pre)(?:\s[^<>]+?)?>$#', $v, $m)) {
$x = isset($m[1]) && $m[1] === '/' ? 0 : 1;
}
$text .= $v; // this is a HTML tag…
} else {
$text .= !$x ? replace($v) : $v; // process or skip…
}
}
return $text;
Taken from here.
In JS you can do:
var chs = "[](){}";
var str = "hello[asd]}";
if (str.indexOf(chs) != -1) {
alert("The string can't contain the following characters: " + chs.split("").join(", "));
}
How can you do this in PHP (replacing alert with echo)?
I do not want to use a regex for the simplicity of what I think.
EDIT:
What I've tried:
<?php
$chs = /[\[\]\(\)\{\}]/;
$str = "hella[asd]}";
if (preg_match(chs, str)) {
echo ("The string can't contain the following characters: " . $chs);
}
?>
Which obviously doesn't work and idk how to do it without regex.
In php you should do this:
$string = "Sometring[inside]";
if(preg_match("/(?:\[|\]|\(|\)|\{|\})+/", $string) === FALSE)
{
echo "it does not contain.";
}
else
{
echo "it contains";
}
The regex says check to see any of the characters are inside the string. you can read more about it here:
http://en.wikipedia.org/wiki/Regular_expression
And about PHP preg_match() :
http://php.net/manual/en/function.preg-match.php
Update:
I have written an updated regex for this, which captures the letters inside:
$rule = "/(?:(?:\[([\s\da-zA-Z]+)\])|\{([\d\sa-zA-Z]+)\})|\(([\d\sa-zA-Z]+)\)+/"
$matches = array();
if(preg_match($rule, $string, $matches) === true)
{
echo "It contains: " . $matches[0];
}
It returnes something like this:
It contains: [inside]
I have changed the regex only which becomes:
$rule = "/(?:(?:(\[)(?:[\s\da-zA-Z]+)(\]))|(\{)(?:[\d\sa-zA-Z]+)(\}))|(\()(?:[\d\sa-zA-Z]+)(\))+/";
// it returns an array of occurred illegal characters
It now returns [] for this "I am [good]"
Why not you try str_replace.
<?php
$search = array('[',']','{','}','(',')');
$replace = array('');
$content = 'hella[asd]}';
echo str_replace($search, $replace, $content);
//Output => hellaasd
?>
Instead of regex we can use string replace for this case.
here is a simple solution without using regex:
$chs = array("[", "]", "(", ")", "{", "}");
$string = "hello[asd]}";
$err = array();
foreach($chs AS $key => $val)
{
if(strpos($string, $val) !== false) $err[]= $val;
}
if(count($err) > 0)
{
echo "The string can't contain the following characters: " . implode(", ", $err);
}