Say I have an integer 88123401, and I want to determine whether it includes a sequence of numbers like 1234, 23456, 456789, or the like of any length and from any beginning of numbers.. Is this possible at all in PHP, and if so, how would one go about finding out?
Some function with a for so you go through all the string comparing each character with its predecessor.
function doesStringContainChain($str, $n_chained_expected)
{
$chained = 1;
for($i=1; $i<strlen($str); $i++)
{
if($str[$i] == ($str[$i-1] + 1))
{
$chained++;
if($chained >= $n_chained_expected)
return true;
}else{
$chained = 1;
}
}
return false;
}
doesStringContainChain("6245679",4); //true
doesStringContainChain("6245679",5); //false
use a loop and use the answer of #jtheman
$mystring = '88123401';
$findme = array(123,2345,34567);
foreach ( $findme as $findspecificnum ) {
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
}
keeping it easy and straight forward.
Treat the number as a string and search with strpos().
Example:
$mystring = '88123401';
$findme = '1234';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
Source: http://php.net/manual/en/function.strpos.php
This might help you:
$number = "88123401";
$splittedNumbers = str_split($number);
$continuous = false;
$matches[0] = '';
$i = 0;
do {
if ((int)(current($splittedNumbers) + 1) === (int)next($splittedNumbers)) {
if($continuous) {
$matches[$i] .= current($splittedNumbers);
}
else {
$matches[$i] .= prev($splittedNumbers) . next($splittedNumbers);
$continuous = true;
}
} else {
$continuous = false;
$matches[++$i] = '';
}
prev($splittedNumbers);
} while (!(next($splittedNumbers) === false));
print_r(array_values(array_filter($matches)));
This lists all the matches that are sequential in an array. We can process further based on the results.
Result:
Array
(
[0] => 1234
[1] => 01
)
Related
Im creating a function to check whether a string contains a specific character prefixed,I need to validate the text based on two conditions.
1.if the string contains character + prefixed ,i have to show the text in output without prefix +.
eg:
"we have dinner +today"
output:
"we have dinner today"
2.if the string contains character - prefixed ,i have to show the text in output removing the whole text prefixed with -.
eg:
"we have dinner -today"
output:
"we have dinner".
I will pass an extra parameter called length in this function ,If the string length is less than the given length then the string will be removed.
eg:
length=4;
eg:
"we have dinner -today"
output:
"have dinner".
eg:
"we have dinner +today"
output:
"have dinner today".
The function i have created so far is
$fulltext="-through the +use of the +tab +key";
$length=4;
function checkstring($fulltext,$length)
{
$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value)
{
if(strlen($value) < $length)
$fulltext= str_replace(" ".$value." " ," ",$fulltext);
}
return $fulltext;
}
print_r(checkstring($fulltext,$length));
The output should be "use tab key"
You can iterate over the words and check if the conditions are checked to keep in the sentence.
$fulltext = "-through the +use of the +tab +key";
$length = 4;
function checkstring($fulltext, $length)
{
$words = preg_split('~\s~',$fulltext);
$remains = [];
foreach ($words as $word)
{
if (strpos($word, '-') === 0) {
continue;
}
if (strpos($word, '+') === 0) {
$word = substr($word, 1);
}
elseif (strlen($word) <= $length) {
continue;
}
$remains[] = $word;
}
return trim(implode(' ', $remains));
}
echo checkstring($fulltext, $length);
Output :
use tab key
View the online demo.
You can use this
if(ctype_alnum($fulltext)) {
echo 'Does not contain symbols';
} else {
echo 'Contains symbols';
}
One way is to use regular expressions to find matching string with correct length and prefixed symbol. If the prefix equals '+' you can then replace the match with string without prefix.
Take a look at preg_replace_callback() and example below.
/* a unix-style command line filter to convert uppercase
* letters at the beginning of paragraphs to lowercase */
<?php
$line = "<p>Start of the paragraph</p>";
$line = preg_replace_callback(
'|<p>\s*\w|',
function ($matches) {
return strtolower($matches[0]);
},
$line
);
echo $line;
?>
function checkstring($fulltext, $length)
{
$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value) {
if ($value[0] == "-") {
$fulltext = str_replace($value, " ", $fulltext);
} else if ($value[0] == "+") {
$fulltext = str_replace($value, substr($value, 1), $fulltext);
}
if (strlen($value) < $length)
$fulltext = str_replace(" " . $value . " ", " ", $fulltext);
}
return $fulltext;
}
Here is the complete function
Using regex
function checkstring(string $fulltext,int $length){
$matches = []; preg_match_all('/[+|-](.[\w]+)/',$fulltext,$matches);
$text = "";
if(isset($matches[1]) && count($matches[1]) > 0)
for($i=0;$i<count($matches[1]);$i++)
if($matches[0][$i][0] == "+" && ($matches[0][$i][0] == "+" && strlen($matches[1][$i]) < $length))
$text .= $matches[1][$i] . " ";
return trim($text);
}
$fulltext="-through the +use of the +tab +key";
$length = 4;
echo checkstring($fulltext,$length);
Output
use tab key
I have two strings abc and bca. I want to check whether an other string contains these both the strings and are not overlapped too. For example:
a string abca contains both but is overlapped.
a string abcxbca contains both and not overlapped.
a string abcxbcabc contains both but is overlapped.
Enjoy :)
<?php
$y1="abc"; //search string1
$y2="bca"; //search string2
$x1="abca"; //contains both but is overlapped.
$x2= "abcxbca"; //contains both and not overlapped.
$x3 ="abcxbcabc"; //contains both but is overlapped.
class Points{
public $start;
public $stop;
public $overlaped=false;
private function Points( $s1, $s2 ) {
$this->start=$s1;
$this->stop=$s2;
$this->overlaped=false;
}
public static function create($s1, $s2){
if (is_numeric($s1)&&is_numeric($s2)){
return new Points($s1, $s2);
}
else return NULL;
}
}
function display($arr){
$cnt1=0;
$cnt2=0;
for ($i=0;$i<count($arr);$i++){
if ($arr[$i]->overlaped===true) $cnt1++;
else $cnt2++;
}
return " ".$cnt2." not overlaped and ".$cnt1." overlaped";
}
function strpos_all($haystack, $needle) {
$offset = 0;
$allpos = array();
while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {
$offset = $pos + 1;
$allpos[] = Points::create($pos,$pos+strlen($needle));
}
return $allpos; }
function check($haystack,$needle1,$needle2){
$find1= strpos_all($haystack, $needle1);
$find2= strpos_all($haystack, $needle2);
for ($i=0;$i<count($find1);$i++){
for($j =0; $j<count($find2);$j++){
if (max($find1[$i]->start,$find2[$j]->start) <= min($find1[$i]->stop,$find2[$j]->stop)) {
$find1[$i]->overlaped=true;
$find2[$j]->overlaped=true;
}
}
}
echo $needle1.display($find1)."<br>";
echo $needle2.display($find2)."<br>";
}
echo "<br>------Start-------<br>";
echo "String :".$x1."<br>";
check ($x1,$y1,$y2);
echo "<br>-----End----------<br>";
echo "<br>------Start-------<br>";
echo "String :".$x2."<br>";
check ($x2,$y1,$y2);
echo "<br>-----End--------<br>";
echo "<br>------Start-------<br>";
echo "String :".$x3."<br>";
check ($x3,$y1,$y2);
echo "<br>-----End--------<br>";
?>
let's say I have 2 set of string to check.
$string = 12345;
$string2 = 15000;
//string must contain 1,2,3,4,5 to be returned true
if(preg_match('[1-5]',$string) {
return true;
} else {
return false;}
This code works for $string but not for $string2. It returns true too with $string2.
Please help!
If string must contain 1, 2, 3, 4 and 5, then you should use regex pattern
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5).*/
which can be further optimize... for example:
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4).*5/
If no other characters are allowed, then you should use regex pattern
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)[1-5]*$/
You can check this with strpos as well:
<?php
function str_contains_all($string, $searchValues, $caseSensitive = false) {
if (!is_array($searchValues)) {
$searchValues = (string)$searchValues;
$searchValuesNew = array();
for ($i = 0; $i < strlen($searchValues); $i++) {
$searchValuesNew[] = $searchValues[$i];
}
$searchValues = $searchValuesNew;
}
$searchFunction = ($caseSensitive ? 'strpos' : 'stripos');
foreach ($searchValues as $searchValue) {
if ($searchFunction($string, (string)$searchValue) === false) {
return false;
}
}
return true;
}
?>
Use:
<?php
$string = 12345;
$string2 = 15000;
if (str_contains_all($string, 12345)) {
echo 'Y';
if (str_contains_all($string2, 12345)) {
echo 'Y';
} else {
echo 'N';
}
} else {
echo 'N';
}
?>
Which outputs:
YN
DEMO
Let's say that I have:
$strPar = "This is a simple paragraph that we will use for the questioning";
$strFindMe = "that";
How will I check if $strPar contains $strFindMe?
Fastest way is to use strpos:
$exists = strpos($strPar, $strFindMe);
if ($exists !== false) {
// substring is in the main string
}
try something like this
if (false !== strpos($strPar, $strFindMe ) )
$string = "This is a strpos() test";
$pos = strpos($string, "i", 3);
if ($pos === false) {
print "Not found\n";
}else{
print "Found at $pos!\n";
}
<?php
$strPar = "This is a simple paragraph that we will use for the questioning";
$strFindMe = "that";
$pos = strpos($strPar, $strFindMe);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Check with strpos() function, it is case sensitive!
if( strpos($strPar, $strFindMe) ) { //it return a boolean value
echo "String Found";
}
$strPar = "This is a simple paragraph that we will use for the questioning";
$strFindMe = "THAT";//Find the position of the first occurrence of a case-insensitive substring in a string
$exists = strpos($strPar, $strFindMe);
if ($exists !== false) {
// substring is in the main string
}
I have looked around the internet for something that will do this but it will only work with one word.
I am trying to build a script that will detect a bad username for my site, the bad username will be detected if the username contains any of the words in an array.
Here's the code I made, but failed to work.
$bad_words = array("yo","hi");
$sentence = "yo";
if (strpos($bad_words,$sentence)==false) {
echo "success";
}
If anybody could help me, I would appreciate it.
use
substr_count
for an array use the following function
function substr_count_array( $haystack, $needle ) {
$count = 0;
foreach ($needle as $substring) {
$count += substr_count( $haystack, $substring);
}
return $count;
}
You can use this code:
$bad_words = array("yo","hi");
$sentence = "yo you your";
// break your sentence into words first
preg_match_all('/\w+/', $sentence, $m);
echo ( array_diff ( $m[0], $bad_words ) === $m[0] ) ? "no bad words found\n" :
"bad words found\n";
// returns false or true
function multiStringTester($feed , $arrayTest)
{
$validator = false;
for ($i = 0; $i < count($arrayTest); $i++)
{
if (stringTester($feed, $arrayTest[$i]) === false )
{
continue;
} else
{
$validator = true;
}
}
return $validator;
}
//www.ffdigital.net
I believe a sentence is more than one single word
Try
$badwords = array("yo","hi");
$string = "i am yo this is testing";
$word = array_intersect( $badwords,explode(" " , $string));
if(empty($word))
{
echo "Sucess" ;
}
<?php
function isUserNameCorrect()
{
Foreach($badname in $badnames)
{
if(strstr($badname, $enteredname) == false)
{
return false;
}
}
return true;
}
Maybe this helps
Unfortunately, you can't give an Array to functions strpos/strstr directly.
According to PHP.net comments, to do this you need to use (or create your own if you want) function like this:
function strstr_array($haystack, $needle)
{
if ( !is_array( $haystack ) ) {
return false;
}
foreach ( $haystack as $element ) {
if ( stristr( $element, $needle ) ) {
return $element;
}
}
}
Then, just change strpos to the new function - strstr_array:
$bad_words = array("yo","hi");
$sentence = "yo";
if (strstr_array($bad_words,$sentence)==false) {
echo "success";
}
I'd implement this as follows:
$bad_words = array("yo","hi");
$sentence = "yo";
$valid = true;
foreach ($bad_words as $bad_word) {
if (strpos($sentence, $bad_word) !== false) {
$valid = false;
break;
}
}
if ($valid) {
echo "success";
}
A sentence is valid unless it contains at least one word from $bad_words. Note the strict checking (i.e. !==), without this the check will fail when the result of strpos is 0 instead of false.
You're close. You can do it the following way:
$bad_words = array("yo","hi");
$sentence = "yo";
$match = false;
foreach($bad_words as $bad_word) {
if (strpos($bad_word,$sentence) === false) { # use $bad_word, not $bad_words
$match = true;
break;
}
}
if($match) { echo "success"; }