In php is there a way i can check if a string includes a value.
Say i had a string "this & that", could i check if that included "this".
Thanks
UPDATED:
$u = username session
function myLeagues2($u)
{
$q = "SELECT * FROM ".TBL_FIXTURES." WHERE `home_user` = '$u' GROUP BY `compname` ";
return mysql_query($q, $this->connection);
}
That code returns if there is an exact match in the database.
But i put two usernames together like "username1 & username2" and need to check if the username session is present in that field.
Is that a way to do this? It obviously woudn't equal it.
ANOTHER UPDATE:
If i use the like %username% in the sql, will it appear if its just the username. So rather than Luke & Matt being shown, if its just Luke will that show too? I dont want it to, i just want things that arent. Can you put != and LIKE so you only get similar matches but not identical?
Cheers
Use strstr or strpos functions. Although there are regex ways too but not worth for such trivial task there.
Using strstr
if (strstr('This & That', 'This') !== false)
{
// found
}
Using strpos
if (strpos('This & That', 'This') !== false)
{
// found
}
I like stristr the best because it is case insensitive.
Usage example from php.net:
$email = 'USER#EXAMPLE.com';
echo stristr($email, 'e'); // outputs ER#EXAMPLE.com
echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US
based on your update
I think you want to use the like statement
SELECT * FROM table
WHERE home_user LIKE "%username1%" OR home_user LIKE "%username2%"
GROUP BY compname
The % Is your wild card.
<?php>
$string = 'this & that';
if (strpos($string, 'this') === FALSE) {
echo 'this does not exist!';
} else {
echo 'this exists!';
}
?>
What's noteworthy in the check is using a triple equal (forget the actual name). strpos is going to return 0 since it's in the 0th position. If it was only '== FALSE' it would see the 0 and interpret it as FALSE and would show 'this does not exist'. Aside from that this is about the most efficient way to check if something exists.
preg_match('/this/','this & that');
This returns the number of matches, so if it's 0, there were no matches. It will however stop after 1 match.
Regular expressions can be checked with preg-match.
Related
Can't find a solution to this which seems simple enough. I have user input field and want to check the user has prefixed the code asked for with an S (example code S123456 so I want to check to make sure they didn't just put 123456).
// Function to check string starting with s
if (isset($_REQUEST['submitted'])) { $string=$_POST['required_code'];function startsWith ($string, $startString){$len = strlen($startString);return (substr($string, 0, $len) === $startString);
}
// Do the check
if(startsWith($string, "s"))echo "Code starts with a s";else echo "Code does not start with a s";}
The problem is if the user inputs an upper case S this is seen as not being a lower case s.
So I can get round this using
$string = strtolower($string);
So if the user inputs an uppercase S it gets converted to lower case before the check. But is this the best way? Is there not someway to say S OR s?
Any suggestions?
What you could do instead of creating your own function, is using stripos. Stripos tries to find the first occurrence of a case-insensitive substring.
So as check you could have:
if(stripos($string, "s") === 0)
You need 3 equal signs, since stripos will return false (0) if it can't find the substring.
Take your pick; there are many ways to see if a string starts with 'S'. Some of them case-sensitive, some not. The options below should all work, although I wouldn't consider any of them better than your current solution. stripos() is probably the 'cleanest' check though. If you need multibyte support, there's also the mb_stripos() variant.
(Although; keep in mind that stripos() can also return false. If you're going with that option, always use the stricter "identical" operator ===, instead of == to prevent type juggling.)
if (stripos($string, 's') === 0) {
// String starts with S or s
} else {
// It does not
}
if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...
if (in_array(substr($string, 0, 1), ['S', 's'], true)) // ...
if (preg_match('/^s/i', $string)) // ...
// Many other regexp patterns also work
Thanks all, it was
if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...
I was looking for I had tried
if (str_starts_with($string, 's' || 'S')) // ...
i have a variable and i want to use php to check if it contains a group of characters
i would like the code to be like this
$groupofcharacters = ["$","#","*","("];
if($variable contains any of the letters in $groupofcharacters){
//do something}
i know that this will need the use of strpos() function but how can i use the strpos function to check if a variable contains a group of characters without me having to create a strpos() function for all the characters that i want to check for.
please if you don't understand you can tell me in the comments
Best way to solve your issue is by using RegEx. Try this:
<?php
$variable = 'Any string containing $*(#';
$sPattern = '/[$#*(]/';
if (preg_match($sPattern, $variable)) {
// Do something
}
You can use strpbrk to achieve this. The doc says:
strpbrk — Search a string for any of a set of characters
Returns a string starting from the character found, or FALSE if it is not found.
Snippet:
<?php
if(strpbrk($variable,"$#*(") !== false){
// your logic goes here
}
check if it has any char. Using strpos
First you need to combine the array as string after check ot if there's one of them in the
$groupofcharacters = ["$","#","*","("];
$strs = implode("", $groupofcharacters);
foreach(str_split($variable) as $s) {
if (strpos($s, $strs)) {
echo "it contains "; continue;
}
}
I am having multiple paragraphs which were coming in loop dynamically. I just want to add a prefix to those paragraphs after checking that a paragraph's first word contains a keyword I am looking for.
I tried many times yet I am unable to get a perfect answer.
$var="Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";
if (stripos($var, 'hello,') !== false) {
echo 'true';
}
Please help with this. I received many similar, related answers but I didn't get the expected one. I am looking to make it work with with case-insensitive.
I am not 100% sure if understand your question right, but maybe you can try this.
$var = "Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";
if (stripos($var, 'hello,') === 0) {
// this checks if the searched word is exactly at the beginning of the string
$var = 'YOUR PREFIX -- ' . $var;
}
echo $var;
If you want to replace the first word, then you should use that code.
$var = "Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";
if (stripos($var, 'hello,') === 0) {
// this checks if the searched word is exactly at the beginning of the string
$var = preg_replace('/hello\,/i', 'REPLACE WITH', $var, 1);
}
echo $var;
You can use strpos
if(strpos($var, 'Hello,') === 0 || strpos($var, 'hello,') === 0){
//Your Logic
}
I had a discussion with my teacher about the mb_ functions. Whatever, one thing leading to another, we changed the subject and he gave me an example where strpos and strlen could be problematic, according to him:
$input = "something"; # input given by the user
$string = "hello"; # string to match
if ( strpos($input, $string) !== false && strlen($input) < strlen($string) ) {
echo "Correct input";
} else {
echo "Incorrect input";
}
(The question is not about how to match 2 strings)
According to my teacher, there may be a way to validate the statement and execute the code echo "Correct input";.
However, I can't see a flaw in this. Maybe there could be a problem with encoding? Do you have any idea?
okey i think that the flaw will be the if statement logic
how will you use strpos function which check the position of the first occurrence of a substring in a string , and in the same time you want to check if the input is greater than the subject ?
by logic it is impossible
I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10