I have this form, wich outputs some letters and a wordlength. But I've got some problems with getting a right output from my database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$letters = mysql_real_escape_string($_POST['letters']);
$length = mysql_real_escape_string($_POST['length']);
echo "Letters: $letters";
echo "Lengte: $length";
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[$letters]{$length}' ")
or die ('Error: '.mysql_error ());
while ($row=mysql_fetch_array($res)){
echo $row['word'];
echo "<br />";
}
}
else {
echo "Foutje";
}
If I change $length to the integer that was inputted by the form my script works. Copy/pasting [$letters] 6 times works also. I guess there is a problem with quotes but I totaly can't figure out what it exactly is.
Can anyone see what I did wrong?
Thanks.
The {} are being interpreted by PHP as delimiters for the variable inside since you are using a double-quoted string. Change your quoting around with concatenation:
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[" . $letters . "]{" . $length ."}'")
Or double up the {} inside a double-quoted string so the outer pair are interpreted as literals.
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[$letters]{{$length}}' ")
Note, you should also verify that $length contains a positive integer.
if (!ctype_digit($length)) {
// error - length must be an int
}
try doing this:
res=mysql_query("SELECT word FROM words WHERE word REGEXP '[".$letters."]{".$length."}' ")
I have a hunch that the $ is getting intepreted as part of the regex
Related
I have this autogenerated variable:
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
How can I search and save "9999" in this var? I cant use substr cause $var's value is always changing and it is always in another "place" in the variable. It is always 4 numbers.
You can match 4 numbers wrapped by word boundaries or space characters, depending on what you need with regular expression (regex/regexp).
if( preg_match('/\b([0-9]{4})\b/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Note, however, that the word boundary match will also match on non-letter characters (symbols like dollar sign ($), hyphen (-), period (.), comma (,), etc.). So a string of "XYZ ABC 9843-AB YZV" would match the "9843". If you want to just match based on numbers surrounded by white space (spaces, tabs, etc) you can use:
if( preg_match('/(?:^|\s)([0-9]{4})(?:\s|$)/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Using explode is the way to go, we need to turn the string into an array, our variables are separated by white space, so we get a variable every time we face a white space " ", i made another example to understand how explode works.
<?php
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
print_r (explode(" ",$var)); //Display the full array.
$var_search = explode(" ",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
<br>
<?php
$var = "WXYZ+300700Z+32011KT+9999+FEW035+SCT200+24/16+Q1007+NOSIG";
print_r (explode("+",$var)); //Display the full array.
$var_search = explode("+",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
I hop this is what you're looking for
Is this viable?
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
if (strpos($var, '9999') == true {
// blah blah
}
else{
echo 'Value not found'
}
Personally haven't tested this yet, but I think you're looking for something along these lines...
Hello I would use a preg_match regex using this regular expression : \d{4}
here is the solution
var str1 = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
var str2 = "9999";
if(str1.indexOf(str2) != -1){
console.log(str2 + " found");
}
I am looking for a Regex to use in PHP in order to match one character; the # symbol.
For example, if I typed: P#ssword into an input, the Regex will match. If I typed P##ssword into an input, the regex will not match.
Here is my PHP Code that I am using:
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST") {
$conn=mssql_connect('d','dd','d');
mssql_select_db('d',$conn);
if(! $conn )
{
die('Could not connect: ' . mssql_get_last_message());
}
$username = ($_POST['username']);
$password = ($_POST['password']);
if (preg_match("[\W]",$_POST["password"]))
{
if (!preg_match("^[^#]*#[^#]*$",$_POST["password"]))
{
header("location:logingbm.php");
} else {
}
}
if(!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL))
{
if ($_POST["username"])
{
if ($_POST["password"])
{
$result = mssql_query("SELECT * FROM staffportal WHERE email='".$username."' AND
password='".$password."'");
if(mssql_num_rows($result) > 0) {
$_SESSION['staff_logged_in'] = 1;
$_SESSION['username'] = $username;
}}}} else {
if ($_POST["password"])
{
$result = mssql_query("SELECT * FROM staffportal WHERE email='".$username."' AND
password='".$password."'");
if(mssql_num_rows($result) > 0) {
$_SESSION['staff_logged_in'] = 1;
$_SESSION['username'] = $username;
}}}}
if(!isset($_SESSION['staff_logged_in'])) {
header("location:logingbm.php");
echo "<script>alert('Incorrect log-in information!');</script>";
} else {
header("location:staffportal.php");
}
?>
Other lightweight approaches...
Without regex
Just use substr_count (see demo)
<?php
$str1 = "pa#s#s";
$str2 = "pa#ss";
echo (substr_count($str1,"#")==1)?"beauty\n":"abject\n"; // abject
echo (substr_count($str2,"#")==1)?"beauty\n":"abject\n"; // beauty
With regex
EDIT: just saw that Sam wrote something equivalent.
If you want to use regex, you could use this fairly simple regex:
#
How? This code (see demo)
<?php
$str1 = "pa#s#s";
$str2 = "pa#ss";
$regex = "~#~";
echo (preg_match_all($regex,$str1,$m)==1)?"beauty\n":"abject\n"; // abject
echo (preg_match_all($regex,$str2,$m)==1)?"beauty\n":"abject\n"; // beauty
The easiest way would be to use the return value of preg_match_all().
Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.
Example:
$count = preg_match_all('/#/', $password, $matches);
Non regex solution (based off of #cdhowie's comment):
$string = 'P#ssword';
$length = strlen($string);
$count = 0;
for($i = 0; $i < $length; $i++) {
if($string[$i] === '#') {
$count++;
}
}
This works because you can access characters of Strings as you would with normal arrays ($var = 'foo'; $var[0] = 'f';).
As I said in my comment, your pattern needs delimiters /, #, ~ or whatever you want (see the PHP doc for that and test yourself).
To be quickly sure that a string contains only one #, you can do that:
if (preg_match('~\A[^#]*#[^#]*\z~', $yourstr))
echo 'There is one #';
else
echo 'There is more than one # or zero #';
This regexp will do what you want:
^[^#]*#[^#]*$
This matches any line that contains one and only one #.
Explanation
^ matches the beginning of the line
[^#]* matches everything before the #
# matches the # character
[^#]* matches everything after the #
$ matches the end of the line
Use
preg_match("#^[^#]*#[^#]*$#", $passwd); //Matches $passwd if it contains only one character
Here's what your regex code means:
If there is at least one non-word character in the string ([\W]), there must be exactly one at-sign (#). There may be any number of any other characters before and after the at-sign: letters, digits, control characters, punctuation, anything. Anything but #.
What I'm wondering is, are you trying to say there can be not more than one at-sign (i.e. zero or one?) That's pretty simple, conceptually; just get rid of the first regex check ("[\W]") and change the second regex to this:
"^[^#]*(?:#[^#]*)?$"
In other words:
Start by consuming not at-signs you see. If you see a #, go ahead and consume it, then resume matching whatever not at-signs remain. If that doesn't leave you at the end of the string, it can only mean there were more than one #. Abandon the attempt immediately and report a failed match.
Of course, this still leaves you with the problem of which other characters you want to allow. I'm pretty sure [^#]* is not what you want.
Also, "[\W]" may be working as you intended, but it's only by accident. You could have written it "/\W/" or "~\W~" "(\W)" and it would work just the same. You may have meant those square brackets to form a character class, but they're not even part of the regex; they're the regex delimiters.
So why did it work, you ask? \W is a predefined character class, equivalent to [^\w]. You can use it inside a regular character class, but it works fine on its own.
I would like to check and see if a given string contains any characters or if it is just all white space. How can I do this?
I have tried:
$search_term= " ";
if (preg_match('/ /',$search_term)) {
// do this
}
But this affects search terms like this as well:
$search_term= "Mark Zuckerburg";
I only want a condition that checks for all white space and with no characters.
Thanks!
ctype_space does this.
$search_term = " ";
if (ctype_space($search_term)) {
// do this
}
The reason your regular expression doesn’t work is that it’s not anchored anywhere, so it searches everywhere. The right regular expression would probably be ^\s+$.
The difference between ctype_space and trim is that ctype_space returns false for an empty string. Use whatever’s appropriate. (Or ctype_space($search_term) || $search_term === ''…)
Use trim():
if(trim($search_term) == ''){
//empty or white space only string
echo 'Search term is empty';
}
trim() will cut whitespace from both start and end of a string - so if the string contains only whitespace trimming it will return empty string.
I would like to know how I could find out in PHP if a variable only contains 1 word. It should be able to recognise: "foo" "1326" ";394aa", etc.
It would be something like this:
$txt = "oneword";
if($txt == 1 word){ do.this; }else{ do.that; }
Thanks.
I'm assuming a word is defined as any string delimited by one space symbol
$txt = "multiple words";
if(strpos(trim($txt), ' ') !== false)
{
// multiple words
}
else
{
// one word
}
What defines one word? Are spaces allowed (perhaps for names)? Are hyphens allowed? Punctuation? Your question is not very clearly defined.
Going under the assumption that you just want to determine whether or not your value contains spaces, try using regular expressions:
http://php.net/manual/en/function.preg-match.php
<?php
$txt = "oneword";
if (preg_match("/ /", $txt)) {
echo "Multiple words.";
} else {
echo "One word.";
}
?>
Edit
The benefit to using regular expressions is that if you can become proficient in using them, they will solve a lot of your problems and make changing requirements in the future a lot easier. I would strongly recommend using regular expressions over a simple check for the position of a space, both for the complexity of the problem today (as again, perhaps spaces aren't the only way to delimit words in your requirements), as well as for the flexibility of changing requirements in the future.
Utilize the strpos function included within PHP.
Returns the position as an integer. If needle is not found, strpos()
will return boolean FALSE.
Besides strpos, an alternative would be explode and count:
$txt = trim("oneword secondword");
$words = explode( " ", $txt); // $words[0] = "oneword", $words[1] = "secondword"
if (count($words) == 1)
do this for one word
else
do that for more than one word assuming at least one word is inputted
I writing a php function to check existence of bad whole words (keep in mind whole word not sub-strings) and also highlight whole words in given string.
function badwordChecherAndHighLighter($str,$replace){
// $replace=1 will Highlight
// $replace=0 will Check the existence of any badwords
$result = mysql_query("SELECT settings_badwords_en,settings_badwords_ar FROM settings_badwords WHERE settings_badwords_status=1") or die(mysql_error());
// i dont create an array, may create overhead, so i directly apply in preg_replace
if($replace==1){
while($row = mysql_fetch_row($result))
{
//$str=preg_replace('/'.$row[0].'/i', str_repeat("*",strlen($row[0])), $str);
$str=preg_replace('/\b('.$row[0].'\b)/i',"" .$row[0] . "" , $str);
$str=preg_replace('/\b('.$row[1].'\b)/i',"" .$row[1] . "" , $str);
}
return $str;
}else{
while($row = mysql_fetch_row($result))
{
if(preg_match('/\b('.$row[0].'\b)/i',$str)) return 1;
if(preg_match('/\b('.$row[1].'\b)/i',$str)) return 1;
}
return 0;
}
}
// $row[1] conatin Arabic bad Words, and $row[0] contain English bad words.
This function gives correct results on Windows OS, WAMP5 1.7.3 for both Arabic and English.
But on Web Server It only works for English words, and not for Arabic.
So if Arabic text is given to this function , it is unable to check existence of any badword, and also unable to highlight arabic word.
I searched and try many options including \u but no error, no success.
So please help.
The \b is not compatible the utf8 characters. Try this:
preg_match('/(?<=^|[^\p{L}])' . preg_quote($utf8word,'/') . '(?=[^\p{L}]|$)/ui',$utf8string);