I need a regular expression to find out whether the string prefix to the number (_number) and if there is to get this number
//Valid
if (preg_match('/^([a-zA-Z0-9_])+([_])+([0-9]).html$/i', 'this_is_page_15.html'))
{
$page = 15;
}
//Invalid
if (preg_match('/^([a-zA-Z0-9_])+([_])+([0-9]).html$/i', 'this_is_page15.html')) // return false;
If I'm understanding you correctly, you would probably want some kind of function to do this. preg_match will return a 1 if it finds a match, a 0 if no match is found, and FALSE if there is an error. You need to supply the 3rd parameter $matches to capture the matched strings (details here: http://php.net/manual/en/function.preg-match.php).
function testString($string) {
if (preg_match("/^\w+_(\d+)\.html/",$string,$matches)){
return $matches[1];
} else {
return false;
}
}
So testString('this_is_page_15.html') will return 15, and testString('this_is_page15.html') will return FALSE.
$str = 'this_is_page_15.html';
$page;
if(preg_match('!_\d+!', $str, $match)){
$page = ltrim($match[0], "_");
}else{
$page = null;
}
echo $page;
//output = 15
Related
How can I get a string that contains a-zA-Z0-9-=&_. and not get a string 0-9
Example php:
$text1 = "2017";
$text2 ="php 2017";
Example function:
function allow($str) {
if (preg_match("/[^a-zA-Z0-9\-=&_.]+/",$str)) {
return $str;
}else{
return false;
}
return $str;
}
like example
text 1 <- false.
text2 <- true.
Try this;
function allow($str) {
if (preg_match("/^[0-9]+$/", $str)) {
return false;
}
return true;
}
What about if $str equals to ""? This function returns true for "".
Edit: is_numeric may be faster than regular expression.
function allow($str) {
if (is_numeric($str)) {
return false;
}
return true;
}
I'm basically just trying to store or access the found string as usable variable (that can be echo'd outside of this function).
Here's the code for my function;
function strposa($haystack, $needle, $offset=0)
{
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query)
{
if(stripos($haystack, $query, $offset) !== false) return $query;
}
return false;
}
So once it finds a match, how do I then echo out the match in my html using
<?php echo $found; ?>
Here's an idea of how it's being used....
$haystack = 'May contain traces of nuts';
$needle = array('gluten','nuts','milk');
$found = strposa($haystack, $needle, $offset);
if(strposa($haystack, $needle, 0)) {
echo $found;
};
This is currently producing bool(false) using the above function.
It's kind of odd that needle is an array and not haystack, but ignoring that, you have two issues:
First, you need to return the value and not the key:
function strposa($haystack, $needle, $offset=0)
{
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query)
{
if(stripos($haystack, $query, $offset) !== false) return $query;
}
return false;
}
Second, you need to assign the return to something:
<?php $found = strposa($haystack, $needle, $offset); ?>
<?php echo $found; ?>
But since it may be returning false, you'll need to test for that in the above assignment or before echoing:
if($found = strposa($haystack, $needle, $offset)) {
echo $found;
}
Using preg_match() with piped needles in your case-insensitive regex pattern removes the need for a custom function that uses a loop AND will allow you to better customize your search if/when your terms yield false positives due to the string existing inside of the a larger/different word.
I have displayed 3 working examples. The first is without an offset and works as expected. The second is without an offset and highlights a potential pitfall with any string search method. The third uses an offset and works as expected.
$needle = array('gluten','nuts','milk');
$regex="/".implode("|",$needle)."/i";
// $regex = /gluten|nuts|milk/i
$haystack = 'May contain traces of nuts';
if(preg_match($regex,$haystack,$match)){
$found=$match[0];
}else{
$found="Not Found"; // false
}
echo "<div>Found = $found</div>";
// TRUE POSITIVE:
// Output: Found = nuts
$haystack = 'This recipe is gluten-free!';
if(preg_match($regex,$haystack,$match)){
$found=$match[0];
}else{
$found="Not Found"; // false
}
echo "<div>Found = $found</div>";
// FALSE POSITIVE:
// Output: Found = gluten
// improve your regex pattern as needed
// for instance use: $regex="/\b".implode("\b|\b",$needle)."\b/i";
// against $haystack="May contain bits of shell from coconuts";
// and it will return "Not Found" because of the word boundaries
$haystack = 'Who put nuts in my milk?!';
$offset=12; // start beyond nuts
if(preg_match($regex,substr($haystack,$offset),$match)){
$found=$match[0];
}else{
$found="Not Found"; // false
}
echo "<div>Found = $found</div>";
// TRUE POSITIVE:
// Output: Found = milk
I have this function to check for word sequences:
function sequence($arr_scheme = [], $arr_input = [])
{
$sequence_need = array_values(array_intersect($arr_scheme, $arr_input));
if(!empty($arr_input) && ($sequence_need == $arr_input)):
return true;
else:
return false;
endif;
}
There were my sample and scheme variables:
$sample = "branch of science";
$scheme = "The branch of science concerned of nature and property of matter and energy";
I have converted to array:
$arr_sample = explode(" ",trim(rtrim(rtrim($sample,".")," ")));
echo 'Sample:';
var_dump($arr_sample);
$arr_scheme = explode(" ",trim(rtrim(rtrim($scheme,".")," ")));
echo '<br/>Scheme:';
var_dump($arr_scheme);
Now, I check the sequences:
$result = sequence($arr_scheme, $arr_sample);
The result:
echo '<br/>Result:';
var_dump($result);
When I set the variable $sample to
"branch science" the result will return true. This was fine.
However when I set the variable sample to
"branch of science" the result will return false .
Reason - the word of was more than 1, how I can solve this problem?
Find first input word in the scheme (can be multiple).
Then run recursive for rests of arrays.
function sequence($arr_scheme = [], $arr_input = [])
{
if (!$arr_input) return true;
$first = array_shift($arr_input);
$occurences = array_keys($arr_scheme, $first);
if (!$occurences) return false;
foreach ($occurences as $o) { // loop first word occurences
$found = sequence(array_slice($arr_scheme, $o), $arr_input);
if ($found) return true;
}
return false;
}
First word later occurences should not matter anything for match.
So, this tail-recursion function will work even better:
function sequence($arr_scheme = [], $arr_input = [])
{
if (!$arr_input) return true;
$first = array_shift($arr_input);
$index = array_search($arr_scheme, $first);
if ($index === false) return false; // not found
return sequence(array_slice($arr_scheme, $index), $arr_input);
}
You can research more at here. Note: "Returns an array containing all of the values in array1 whose values exist in all of the parameters.". Then, look at in your result, when you call var_dump($arr_scheme);, you see "of" appears 3 times. and size of array result after compare is 5. however, size of array $sample is 3. So, you can understand why it returns false.
Solution for this case. why dont you try to use regular expression? or strpos function?
$sequence_need = array_unique($sequence_need);
array_unique removes any duplicate values in your array.. the duplicate 'of' will be removes.. Hope it helps..
I think you should go with array_diff(). It computes the difference of arrays and returns the values in $arr_sample that are not present in $arr_scheme.
So,
array_diff($arr_sample, $arr_scheme)
will return an empty array if all the values in $arr_sample are present in $arr_scheme
The next step would be to count the length of the array returned by array_diff(). If it equals 0, then we should return true
return count(array_diff($arr_sample, $arr_scheme)) === 0;
The above return statement could be presented as:
$diff = array_diff($arr_sample, $arr_scheme);
if (count($diff) === 0) {
return true;
} else {
return false;
}
From your comments it became clear that your function should return true
if all the elements of $arr_input are present in $arr_scheme in the same order
that they appear in $arr_scheme. Othewise it should return false
So,
sequence(['branch', 'of', 'science', 'and', 'energy'], ['branch', 'of', 'energy'])
should return true
and
sequence(['branch', 'of', 'science', 'and', 'energy'], ['science', 'of', 'branch'])
should return false
In this case the function sequence() could be defined as follows:
function sequence($arr_scheme = [], $arr_input = [])
{
//test if all elements of $arr_input are present in $arr_scheme
$diff = array_diff($arr_input, $arr_scheme);
if ($diff) {
return false;
}
foreach ($arr_input as $value) {
$pos = array_search($value, $arr_scheme);
if (false !== $pos ) {
$arr_scheme = array_slice($arr_scheme, $pos + 1);
continue;
}
return false;
}
return true;
}
This question already has answers here:
String contains any items in an array (case insensitive)
(15 answers)
Closed 2 years ago.
I am trying to detect whether a string contains at least one URL that is stored in an array.
Here is my array:
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
The string is entered by the user and submitted via PHP. On the confirmation page I would like to check if the URL entered is in the array.
I have tried the following:
$string = 'my domain name is website3.com';
if (in_array($string, $owned_urls))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
No matter what is inputted the return is always "Match not found".
Is this the correct way of doing things?
Try this.
$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
//if (strstr($string, $url)) { // mine version
if (strpos($string, $url) !== FALSE) { // Yoshi version
echo "Match found";
return true;
}
}
echo "Not found!";
return false;
Use stristr() or stripos() if you want to check case-insensitive.
This was a lot easier to do if all you want to do is find a string in an array.
$array = ["they has mystring in it", "some", "other", "elements"];
if (stripos(json_encode($array),'mystring') !== false) {
echo "found mystring";
}
Try this:
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$url_string = end(explode(' ', $string));
if (in_array($url_string,$owned_urls)){
echo "Match found";
return true;
} else {
echo "Match not found";
return false;
}
-
Thanks
Simple str_replace with count parameter would work here:
$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
echo "One of Array value is present in the string.";
}
More Info - https://www.techpurohit.in/extended-behaviour-explode-and-strreplace-php
I think that a faster way is to use preg_match.
$user_input = 'Something website2.com or other';
$owned_urls_array = array('website1.com', 'website2.com', 'website3.com');
if ( preg_match('('.implode('|',$owned_urls_array).')', $user_input)){
echo "Match found";
}else{
echo "Match not found";
}
$string = 'my domain name is website3.com';
$a = array('website1.com','website2.com','website3.com');
$result = count(array_filter($a, create_function('$e','return strstr("'.$string.'", $e);')))>0;
var_dump($result );
output
bool(true)
Here is a mini-function that search all values from an array in a given string.
I use this in my site to check for visitor IP is in my permitted list on certain pages.
function array_in_string($str, array $arr) {
foreach($arr as $arr_value) { //start looping the array
if (stripos($str,$arr_value) !== false) return true; //if $arr_value is found in $str return true
}
return false; //else return false
}
how to use
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
//this example should return FOUND
$string = 'my domain name is website3.com';
if (array_in_string($string, $owned_urls)) {
echo "first: Match found<br>";
}
else {
echo "first: Match not found<br>";
}
//this example should return NOT FOUND
$string = 'my domain name is website4.com';
if (array_in_string($string, $owned_urls)) {
echo "second: Match found<br>";
}
else {
echo "second: Match not found<br>";
}
DEMO: http://phpfiddle.org/lite/code/qf7j-8m09
stripos function is not very strict. it's not case sensitive or it can match a part of a word
http://php.net/manual/ro/function.stripos.php
if you want that search to be case sensitive use strpos
http://php.net/manual/ro/function.strpos.php
for exact match use regex (preg_match), check this guy answer https://stackoverflow.com/a/25633879/4481831
You can concatenate the array values with implode and a separator of |
and then use preg_match to search for the value.
Here is the solution I came up with ...
$emails = array('#gmail', '#hotmail', '#outlook', '#live', '#msn', '#yahoo', '#ymail', '#aol');
$emails = implode('|', $emails);
if(!preg_match("/$emails/i", $email)){
// do something
}
If your $string is always consistent (ie. the domain name is always at the end of the string), you can use explode() with end(), and then use in_array() to check for a match (as pointed out by #Anand Solanki in their answer).
If not, you'd be better off using a regular expression to extract the domain from the string, and then use in_array() to check for a match.
$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);
if (empty($matches[1])) {
// no domain name was found in $string
} else {
if (in_array($matches[1], $owned_urls)) {
// exact match found
} else {
// exact match not found
}
}
The expression above could probably be improved (I'm not particularly knowledgeable in this area)
Here's a demo
You are checking whole string to the array values. So output is always false.
I use both array_filter and strpos in this case.
<?php
$urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$check = array_filter($urls, function($url){
global $string;
if(strpos($string, $url))
return true;
});
echo $check?"found":"not found";
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
for($i=0; $i < count($owned_urls); $i++)
{
if(strpos($string,$owned_urls[$i]) != false)
echo 'Found';
}
$message = "This is test message that contain filter world test3";
$filterWords = array('test1', 'test2', 'test3');
$messageAfterFilter = str_replace($filterWords, '',$message);
if( strlen($messageAfterFilter) != strlen($message) )
echo 'message is filtered';
else
echo 'not filtered';
I find this fast and simple without running loop.
$array = array("this", "that", "there", "here", "where");
$string = "Here comes my string";
$string2 = "I like to Move it! Move it";
$newStr = str_replace($array, "", $string);
if(strcmp($string, $newStr) == 0) {
echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
echo 'Word Exists - Some Word from array got replaced!';
}
$newStr = str_replace($array, "", $string2);
if(strcmp($string2, $newStr) == 0) {
echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
echo 'Word Exists - Some Word from array got replaced!';
}
Little explanation!
Create new variable with $newStr replacing value in array of original string.
Do string comparison - If value is 0, that means, strings are equal and nothing was replaced, hence no value in array exists in string.
if it is vice versa of 2, i.e, while doing string comparison, both original and new string was not matched, that means, something got replaced, hence value in array exists in string.
$search = "web"
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
foreach ($owned_urls as $key => $value) {
if (stristr($value, $search) == '') {
//not fount
}else{
//found
}
this is the best approach search for any substring , case-insensitive and fast
just like like im mysql
ex:
select * from table where name = "%web%"
I came up with this function which works for me, hope this will help somebody
$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';
function checkStringAgainstList($str, $word_list)
{
$word_list = explode(', ', $word_list);
$str = explode(' ', $str);
foreach ($str as $word):
if (in_array(strtolower($word), $word_list)) {
return TRUE;
}
endforeach;
return false;
}
Also, note that answers with strpos() will return true if the matching word is a part of other word. For example if word list contains 'st' and if your string contains 'street', strpos() will return true
Can someone help me with algorithm for finding the position of the first occurrence of any number in a string?
The code I found on the web does not work:
function my_offset($text){
preg_match('/^[^\-]*-\D*/', $text, $m);
return strlen($m[0]);
}
echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv');
The built-in PHP function strcspn() will do the same as the function in Stanislav Shabalin's answer when used like so:
strcspn( $str , '0123456789' )
Examples:
echo strcspn( 'That will be $2.95 with a coupon.' , '0123456789' ); // 14
echo strcspn( '12 people said yes' , '0123456789' ); // 0
echo strcspn( 'You are number one!' , '0123456789' ); // 19
HTH
function my_offset($text) {
preg_match('/\d/', $text, $m, PREG_OFFSET_CAPTURE);
if (sizeof($m))
return $m[0][1]; // 24 in your example
// return anything you need for the case when there's no numbers in the string
return strlen($text);
}
function my_ofset($text){
preg_match('/^\D*(?=\d)/', $text, $m);
return isset($m[0]) ? strlen($m[0]) : false;
}
should work for this. The original code required a - to come before the first number, perhaps that was the problem?
I can do regular expressions but I have to go into an altered state to
remember what it does after I've coded it.
Here is a simple PHP function you can use...
function findFirstNum($myString) {
$slength = strlen($myString);
for ($index = 0; $index < $slength; $index++)
{
$char = substr($myString, $index, 1);
if (is_numeric($char))
{
return $index;
}
}
return 0; //no numbers found
}
Problem
Find the first occurring number in a string
Solution
Here is a non regex solution in javascript
var findFirstNum = function(str) {
let i = 0;
let result = "";
let value;
while (i<str.length) {
if(!isNaN(parseInt(str[i]))) {
if (str[i-1] === "-") {
result = "-";
}
while (!isNaN(parseInt(str[i])) && i<str.length) {
result = result + str[i];
i++;
}
break;
}
i++;
}
return parseInt(result);
};
Example Input
findFirstNum("words and -987 555");
Output
-987