how do I say "If a string contains "x" in PHP? - php

I have a variable:
$testingAllDay = $event->when[0]->startTime;
This variable will be this format if it is "All Day":
2011-06-30
It will be this format if it is not "All Day":
2011-07-08T12:00:00.000-05:00
I'm wanting to do something like:
if ($testingAllDay does not contain "T"){
$AllDay = 1;
} else {
$AllDay = 0;
}
Do I need to use a strstr() here, or is there another function that does this? Thanks!

One option is to use strpos to see if the 'T' character is present in the string as follows:
if (strpos($testingAllDay, 'T') !== false) {
// 'T' was present in $testingAllDay
}
That said, it would probably be faster/more efficient (although no doubt meaninglessly so) to use strlen in this case, as according to your example, the time-free field will always be 10 characters long.
For example:
if(strlen($testingAllDay) > 10) {
// 'T' was present in $testingAllDay
}

Use strpos:
if (strpos($testingAllDay,"T")!==false){
or strstr
if (!strstr($testingAllDay,"T")){

if (strpos($testingAllDay, 'T') !== FALSE){
...
}

If those are the only possible cases, even strlen() will do.

not exactly answer to the question, but you could check with strlen().
i.e. "All Day" length is 10, anything above that is not.

The function you're looking for is strpos(). The following is an example picking up your wording for the variable names even:
$testingAllDayTPosition = strpos($testingAllDay, 'T');
$testingAllDayDoesNotContainT = false === $testingAllDayTPosition;
if ($testingAllDayDoesNotContainT){
$AllDay = 1;
} else {
$AllDay = 0;
}

strstr and strpos are two functions by which you can complete your requirement.
strstr will see if substring exists in string and it will echo from first occurrence of string to rest.
While strpos will give you position of first occurrence of the string.

Related

Unable to get the position of a character within my string using strpos

Good day,
I have the following string :
[Star]ALERT[Star]Domoos detects blabla[blabli]
For strange reasons, the code below does not detect the star at the very first character. I read in the php documentation that the first character has an index of 0. However, if I am looking for the '[', the function works very well.
What I am trying to achieve is to ensure that the first character of my string is really a * (star). Strangely, if I enter $pos1 = strpos($inputString, '*', 1), the star shown at position '6' would be returned.
I don't quite understand why my code does not work as expected (i.e. does not enter into the 'true' condition)
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
if ($pos1 == True)
{
echo 'position' . $pos1;
}
Do you have any suggestion that would help me to overcome this issue?
Thanks a lot for your appreciated support.
change condition to
if ($pos1 != False)
{
echo 'position' . $pos1;
}
as strpos will return position at (integer) or False
If you look at the manual:
Find the numeric position of the first occurrence of needle in the
haystack string.
In your test case, the numeric position is 0 and 0 != true.
Also see the warning in the manual:
Warning This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
So the condition you really want is:
if ($pos1 !== false)
You don't need strpos. As string is an array of characters so you can do like this
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$compare_char= $inputString[0];
if($compare_char=="*"){
//do something.
}
As i suppose it is fast too rather than on searching through strpos
Actually issue is that when you are looking at 0 position the value which you get is 0 and when you are checking that in if condition with True, it will always fail because 0 will be evaluated as False. To resolve this you can use
if($pos1 !== False)
The function strpos returns false if there is no existence of what you search. So make a check like the following:
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
return $pos1 !== false ? 'position ' . $pos1 : '..';
$pos1 returns 0 and this is treat as False so we cant take it as True so we can use here isset function.
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*',0);
if (isset($pos1))
{
echo 'position' . $pos1;
}

Complex Name validation with PHP

I am working on a project and a part of it requires to validate name fields.
Here is the logic:
If any name value contains an 'i' after 'e' that is not after 'c',
then issue an error.
I know I should try to write something and then share it, but in this case I have no idea how its done. I know preg_match() can be a solution , but again I have no idea how its done.
I know I will get down vote due to not writing anything, but hopefully I get an answer.
Thanks Guys,
You can use stripos() (or strpos() if case sensitivity is required). To demonstrate:
$str1 = "weird";
$str2 = "ceiling";
checkCEI($str1); // Echoes "Error for weird"
checkCEI($str2); // output true, as it passes the test
function checkCEI($str) {
if (stripos($str, "ei") !== false && stripos($str, "cei") === false) {
return "Error for ".$str;
}
return true;
}
You should use preg_match() as you say.
Here it is your pattern:
[^c]ei - for all strings, where there is NO C berfore EI
$badString = 'ceiling';
$goodString = 'vein';
$pattern = '/[^c]ei/';
preg_match($pattern,$badString); // 0
preg_match($pattern,$goodString); //1
If you want all strings that match with 'cei', you don't need regex.
You can use stripos
$goodString = 'ceiling';
$badString = 'vein';
stripos($badString, 'cei'); // -1
preg_match($goodString,'cei'); //1
Important! Please check manual for returning values of both functions.

PHP strpos to match querystring text pattern

I need to execute a bit of script only if the $_GET['page'] parameter has the text "mytext-"
Querystring is: admin.php?page=mytext-option
This is returning 0:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
echo $match;
strpos returns the position of the string. Since it's 0, that means it was found at position 0, meaning, at the start of the string.
To make an easy way to understand if it's there, add the boolean === to an if statement like this:
<?php
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match === false ) {
echo 'Not found';
} else {
echo 'Found';
}
?>
This will let you know, if the string is present or not.
Or, if you just need to know, if it's there:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match !== false ) {
echo 'Found';
}
?>
Use substr() once you get the location of 'mytext-', like so:
$match = substr($myPage, strpos( $myPage, 'mytext-') + strlen( 'mytext-'));
Otherwise, strpos() will just return the numerical index of where 'mytext-' starts in the string.
You can also use str_replace() to accomplish this if your string only has 'mytext-' once:
$match = str_replace( 'mytext-', '', $myPage);
The function strpos() returns the position where the searched string starts which is 0. If the string is not found, the function will return false. See the strpos documentation which tells you as well:
WARNING This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
A solution to your question would be to use substr(), preg_match() or check if strpos() !== false.
The easiest solution should be this:
if (preg_match('/^mytext-/i', $_GET['page'])) {
// do something
}
You may also consider using more than just one GET parameter like
http://www.example.com/foo.php?page=mysite&option1=123&option2=456
You then use your parameters lik $_GET['page'], $_GET['option1'], $_GET['option2'], etc.
However, you should also be careful what you do with raw $_GETor $_POST data since users can directly input them and may inject harmful code to your website.
That is expected since the substring starts at index 0. Read the warning on php.net/strpos:
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
If you only need to check if $myPage contains 'mytext-', use stristr:
if(stristr($myPage, 'mytext-') !== false) {
// contains..
}
What's wrong about preg_match?
$myPage = $_GET['page'];
if (preg_match("/\bmytext-\b/i", $myPage)) {
//Do Something
}
Or do you need the "option" out of "mytext-option"?
If yes you can use this:
$myPage = $_GET['page'];
$querystrings = explode("-", $myPage);
if ($querystrings[0] == 'mytext')) {
//Do Something
echo $querystrings[1]; //outputs option
}
With this you can even use more "options" in your querystring like "mytext-option-whatever". That's the same as when you use
$_GET['page'], $_GET['option'], $_GET['whatever']
when you use
?page=mysite&option=x&whatever=y

PHP check for string inside string

I have variable x and I want to see if it contains a string like hs even though the value may be cug hs ib ap. Can anybody help me figure this out? Thanks!
PHP strstr
<?php
$x = 'cug hs ib';
$y = strstr($x, 'hs');
echo $y;
?>
Update:
Better user strpos
<?php
$x = 'cug hs ib';
$y = strpos($x, 'hs');
if($y === false)
// Not a substring
else
// Substring
?>
if(strpos($big_string, $sub_string) !== false)
{
// $big_string contains $sub_string
}
You could use strpos
if (strpos($haystack, $needle) !== false) {
echo "the string '{$needle}' was found within '{$haystack}'";
}
You could use substr_count .. http://php.net/substr_count or strpos, http://php.net/strpos
Either strpos() or stripos() (depending on whether you're interested in case sensitivity).
http://php.net/manual/en/function.strpos.php

What's the most efficient test of whether a PHP string ends with another string?

The standard PHP way to test whether a string $str ends with a substring $test is:
$endsWith = substr( $str, -strlen( $test ) ) == $test
Is this the fastest way?
What Assaf said is correct. There is a built in function in PHP to do exactly that.
substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0;
If $test is longer than $str PHP will give a warning, so you need to check for that first.
function endswith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}
This method is a tiny bit more memory-expensive, but it is faster:
stripos(strrev($haystack), $reversed_needle) === 0;
This is best when you know exactly what the needle is, so you can hard-code it reversed. If you reverse the needle programmatically, it becomes slower than the earlier method.
Edit (12 years later): LOL, this is a super-old answer that I wrote when I didn't know what I was actually talking about. I'd like the think I've grown since then. #DavidHarkness is right, it is not very efficient in the negative case. Probably much faster to just iterate in reverse and bail early if you really need as much perf as possible. Also, php probably has better ways to do this now. Honestly, I haven't written php in nearly a decade, so I'll leave it up to others now.
$endsWith = substr_compare( $str, $test, -strlen( $test ) ) === 0
Negative offset "starts counting from the end of the string".
Here’s a simple way to check whether one string ends with another, by giving strpos an offset right where the string should be found:
function stringEndsWith($whole, $end)
{
return (strpos($whole, $end, strlen($whole) - strlen($end)) !== false);
}
Straightforward, and I think this’ll work in PHP 4.
It depends on which sort of efficiency you care about.
Your version uses more memory due to the extra copy from the use of substr.
An alternative version might search the original string for the last occurrence of the substring without making a copy, but would probably be slower due to more testing.
Probably the most efficient way is to do loop char-by-char from the -sterlen(test) position till the end of the string and compare. That's the minimal amount of comparisons you can hope to do and there's hardly any extra memory used.
In PHP 8:
str_ends_with('haystack', 'stack'); // true
str_ends_with('haystack', 'K'); // false
and also:
str_starts_with('haystack', 'hay'); // true
PHP RFC: Add str_starts_with(), str_ends_with() and related functions
Another way would be to use the strrpos function:
strrpos($str, $test) == strlen($str) - strlen($test)
But that’s not faster.
I hope that the below answer may be efficient and also simple:
$content = "The main string to search";
$search = "search";
//For compare the begining string with case insensitive.
if(stripos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the begining string with case sensitive.
if(strpos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case insensitive.
if(stripos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case sensitive.
if(strpos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
Don't know if this is fast or not but for a single character test, these work, too:
(array_pop(str_split($string)) === $test) ? true : false;
($string[strlen($string)-1] === $test) ? true : false;
(strrev($string)[0] === $test) ? true : false;
easiest way to check it via regular expression
for example to check if the mail given is gmail:
echo (preg_match("/#gmail\.com$/","example-email#gmail.com"))?'true':'false';
I'm thinking the reverse functions like strrchr() would help you match the end of the string the fastest.
This is pure PHP, without calling external functions, except for strlen.
function endsWith ($ends, $string)
{
$strLength = strlen ($string);
$endsLength = strlen ($ends);
for ($i = 0; $i < $endsLength; $i++)
{
if ($string [$strLength - $i - 1] !== $ends [$i])
return false;
}
return true;
}
for single-char needle:
if (#strrev($haystack)[0] == $needle) {
// yes, it ends...
}

Categories