PHP: word check for 30 chars - php

I would like to check that if $_POST[msg] contains a word that are longer than 30 chars(without no spaces) so you wouldnt be able to write:
example1 :
asdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsddsasdsdsdsdsd
example2:
hello my name is asdoksdosdkokosdkosdkodskodskodksosdkosdkokodsdskosdkosdkodkoskosdkosdkosdkosdsdksdoksd
(notice no spaces).
How can I do that?

You could use preg_match to look for that as follows...
if (preg_match('/\S{31,}/', $_POST['msg']))
{
//string contains sequence of non-spaces > 30 chars
}
The /S matches any non-space character, and is the inverse of /s which matches any space. See the manual page on PCRE escape sequences

You can use the regex \w{31,} to find for a word that has 31 or more characters:
if(preg_match('/\w{31,}/',$_POST['msg'])) {
echo 'Found a word >30 char in length';
}
If you want to find group of non-space characters that are 31 or more characters in length, you can use:
if(preg_match('/\S{31,}/',$_POST['msg'])) {
echo 'Found a group of non-space characters >30 in length';
}

First find the words:
// words are separated by space usually, add more logic here
$words = explode(' ', $_POST['msg']);
foreach($words as $word) {
if(strlen($word) > 30) { // if the word is bigger than 30
// do something
}
}

How about this? Just difference in logic
if (strlen(preg_replace('#\s+#', '', $_POST['msg'])) > 30) {
//string contain more then 30 length (spaces aren't counted)
}

First split the input into words:
explode(" ", $_POST['msg']);
then get the maximum length string:
max(explode(" ", $_POST['msg']));
and see if that is larger than 30:
strlen(max(explode(" ", $_POST['msg']))) > 30

Related

How to remove a character from a string only if it follows a number?

I have several rows of data that are in address format, I want to remove the house number from each address.
So far I have been able to remove the number using:
<?php
$string = '25a Test Lane';
if (preg_match("/[0-9]/", $string)) {
$string = preg_replace("/[0-9]/", "", $string);
}
?>
$string then becomes 'a Test Lane' - but how would I go about removing 'a' as well? Bearing in mind the 'a' could be any letter following a number. I'd want to remove any character that immediately follows the number (no space in between).
You can use
trim(preg_replace("/\b\d+[a-zA-Z]*\b/", "", $string))
trim(preg_replace("/\b\d+[a-zA-Z]?\b/", "", $string))
Here is the regex demo. NOTE: if you only want to allow a single letter after the number, replace * with ? in [a-zA-Z]*.
Details:
\b - a word boundary
\d+ - one or more digits
[a-zA-Z]* - zero or more ASCII letters
[a-zA-Z]? - one or zero ASCII letters
\b - a word boundary.
See the PHP demo:
$string = '25a Test Lane';
$string = trim(preg_replace("/\b\d+[a-zA-Z]*\b/", "", $string));
echo $string;
// => Test Lane

PHP convert uppercase words to lowercase, but keep ucfirst on lowercase words

An example:
THIS IS A Sentence that should be TAKEN Care of
The output should be:
This is a Sentence that should be taken Care of
Rules
Convert UPPERCASE words to lowercase
Keep the lowercase words with an uppercase first character intact
Set the first character in the sentence to uppercase.
Code
$string = ucfirst(strtolower($string));
Fails
It fails because the ucfirst words are not being kept.
This is a sentence that should be taken care of
You can test each word for those rules:
$str = 'THIS IS A Sentence that should be TAKEN Care of';
$words = explode(' ', $str);
foreach($words as $k => $word){
if(strtoupper($word) === $word || // first rule
ucfirst($word) !== $word){ // second rule
$words[$k] = strtolower($word);
}
}
$sentence = ucfirst(implode(' ', $words)); // third rule
Output:
This is a Sentence that should be taken Care of
A little bit of explanation:
Since you have overlapping rules, you need to individually compare them, so...
Break down the sentence into separate words and check each of them based on the rules;
If the word is UPPERCASE, turn it into lowercase; (THIS, IS, A, TAKEN)
If the word is ucfirst, leave it alone; (Sentence, Care)
If the word is NOT ucfirst, turn it into lowercase, (that, should, be, of)
You can break the sentence down into individual words, then apply a formatting function to each of them:
$sentence = 'THIS IS A Sentence that should be TAKEN Care of';
$words = array_map(function ($word) {
// If the word only has its first letter capitalised, leave it alone
if ($word === ucfirst(strtolower($word)) && $word != strtoupper($word)) {
return $word;
}
// Otherwise set to all lower case
return strtolower($word);
}, explode(' ', $sentence));
// Re-combine the sentence, and capitalise the first character
echo ucfirst(implode(' ', $words));
See https://eval.in/936462
$str = "THIS IS A Sentence that should be TAKEN Care of";
$str_array = explode(" ", $str);
foreach ($str_array as $testcase =>$str1) {
//Check the first word
if ($testcase ==0 && ctype_upper($str1)) {
echo ucfirst(strtolower($str1))." ";
}
//Convert every other upercase to lowercase
elseif( ctype_upper($str1)) {
echo strtolower($str1)." ";
}
//Do nothing with lowercase
else {
echo $str1." ";
}
}
Output:
This is a Sentence that should be taken Care of
I find preg_replace_callback() to be a direct tool for this task. Create a pattern that will capture the two required strings:
The leading word
Any non-leading, ALL-CAPS word
Code: (Demo)
echo preg_replace_callback(
'~(^\pL+\b)|(\b\p{Lu}+\b)~u',
function($m) {
return $m[1]
? mb_convert_case($m[1], MB_CASE_TITLE, 'UTF-8')
: mb_strtolower($m[2], 'UTF-8');
},
'THIS IS A Sentence that should be TAKEN Care of'
);
// This is a Sentence that should be taken Care of
I did not test this with multibyte input strings, but I have tried to build it with multibyte characters in mind.
The custom function works like this:
There will always be either two or three elements in $m. If the first capture group matches the first word of the string, then there will be no $m[2]. When a non-first word is matched, then $m[2] will be populated and $m[1] will be an empty string. There is a modern flag that can be used to force that empty string to be null, but it is not advantageous in this case.
\pL+ means one or more of any letter (single or multi-byte)
\p{Lu}+ means one or more uppercase letters
\b is a word boundary. It is a zero-width character -- it doesn't match a character, it checks that the two consecutive characters change from a word to a non-word or vice versa.
My answer makes just 3 matches/replacement on the sample input string.
$string='THIS IS A Sentence that should be TAKEN Care of';
$arr=explode(" ", $string);
foreach($arr as $v)
{
$v = ucfirst(strtolower($v));
$stry = $stry . ' ' . $v;
}
echo $stry;

How to use substr and strpos to whole word if we don't know string length

I'm trying to show part of a string; 60 characters of it. But it's cut and not displayed to while word. So I tried this:
if(strpos($string, ' ', 50) !== FALSE) {
substr($string, 0, strpos($string, ' ', 50))
}elseif(strlen($string) < 50)) {
echo $string;
}
But now, problem is that I don't know after how many characters there is space.
I've checked if there is space after 50 characters and show this sub-string. But if word is with many characters, how to check its length, so that my final sub-string is not more than 60 characters?
Is there better solution to this kind of showing sub-string to whole word?
This should return whole words and not break a word if it happens to be at the upper limit of 60
$maxlength=60;
$str_text="But now, problem is that I don't know after how many characters there is space.
I've checked if there is space after 50 characters and show this substring. But if word is
with many characters, how to check its length, so that my final substring is not more than
60 characters?";
$trimmed=rtrim( preg_replace('/\s+?(\S+)?$/', '', substr( $str_text, 0, $maxlength+1 ) ), ',' );
echo $trimmed;
Consider this example:
<?php
$subject = <<<EOT
But now, problem is that I don't know after how many characters there is space.
I've checked if there is space after 50 characters and show this substring.
But if word is with many characters, how to check its length, so that my final substring is not more than 60 characters?
EOT;
$lastBlankPos = strrpos(substr($subject, 0, 60), ' ');
var_dump(substr($subject, 0, $lastBlankPos));
The output is:
string(52) "But now, problem is that I don't know after how many"
The strategy is: look for the last blank contained in the first 60 characters of the string. This guarantees that you terminate your substring with a "whole word" whilst still staying right under 60 characters in length. strrpos() is a handy function for that: http://php.net/manual/en/function.strrpos.php

Finding and replacing all words that ends with 'ing'

I'm trying to find and replace all words that ends with 'ing'. How would I do that?
$text = "dreaming";
if (strlen($text) >= 6) {
if (0 === strpos($text, "ing"))
//replace the last 3 characters of $text <---not sure how to do this either
echo $text;
echo "true";
}
Result:
null
Want Result:
dream
true
You could also use substr
$text = "dreaming";
if (substr($text, (strlen($text) - 3), 3) === 'ing') {
$text = substr($text, 0, (strlen($text) - 3));
}
echo $text;
This should work for replacing ing at the end of words whilst ignoring stuff starting with Ing as well as words with ing in the middle of them.
$output = preg_replace('/(\w)ing([\W]+|$)/i', '$1$2', $input);
Updated to reflect change specified in comments.
You could use two regexs depending on what you are trying to accomplish your question is a bit ambiguous.
echo preg_replace('/([a-zA-Z]+)ing((:?[\s.,;!?]|$))/', '$1$2', $text);
or
echo preg_replace('/.{3}$/', '', $text);
The first regex looks for word characters before an ing and then punctuation marks, white spaces, or the end of the string. The second just takes off the last three characters of the string.
You can use regex and word boundaries.
$str = preg_replace('/\Bing\b/', "", $str);
\B (non word boundary) matches where word characters are sticking together.
Be aware it substitutes king to k. See demo at regex101

Allow only [a-z][A-Z][0-9] in string using PHP

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?
You can filter it like:
$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
As for some symbols, you should be more specific
You can test your string (let $str) using preg_match:
if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
// string only contain the a to z , A to Z, 0 to 9
}
If you need more symbols you can add them before ]
Don't need regex, you can use the Ctype functions:
ctype_alnum: Check for alphanumeric character(s)
ctype_alpha: Check for alphabetic character(s)
ctype_cntrl: Check for control character(s)
ctype_digit: Check for numeric character(s)
ctype_graph: Check for any printable character(s) except space
ctype_lower: Check for lowercase character(s)
ctype_print: Check for printable character(s)
ctype_punct: Check for any printable character which is not whitespace or an alphanumeric character
ctype_space: Check for whitespace character(s)
ctype_upper: Check for uppercase character(s)
ctype_xdigit: Check for character(s) representing a hexadecimal digit
In your case use ctype_alnum, example:
if (ctype_alnum($str)) {
//...
}
Example:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo 'The string ', $testcase, ' consists of all letters or digits.';
} else {
echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';
}
}
Online example: https://ideone.com/BYN2Gn
Both these regexes should do it:
$str = preg_replace('~[^a-z0-9]+~i', '', $str);
Or:
$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
A shortcut will be as below also:
if (preg_match('/^[\w\.]+$/', $str)) {
echo 'Str is valid and allowed';
} else
echo 'Str is invalid';
Here:
// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
\w - matches [a-zA-Z0-9_]+
Hope it helps!
If you need to preserve spaces in your string do this
$text = preg_replace("/[^a-zA-Z0-9 ]+/", "", $text);
Please note the way I have added space between 9 and the closing bracket. For example
$name = "!#$John Doe";
echo preg_replace("/[^a-zA-Z0-9 ]+/", "", $name);
the output will be:
John Doe
Spaces in the string will be preserved.
If you fail to include the space between 9 and the closing bracket the output will be:
JohnDoe
Hope it helps someone.
The best and most flexible way to accomplish that is using regular expressions.
But I`m not sure how to do that in PHP but this article can help. link

Categories