PHP strpos to match querystring text pattern - php

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

Related

Creating a New Variable Based On a Matched Array ID Value [duplicate]

<?php
$a = 'abc';
if($a among array('are','abc','xyz','lmn'))
echo 'true';
?>
Suppose I have the code above, how to write the statement "if($a among...)"?
Use the in_array() function.
Manual says:
Searches haystack for needle using loose comparison unless strict is set.
Example:
<?php
$a = 'abc';
if (in_array($a, array('are','abc','xyz','lmn'))) {
echo "Got abc";
}
?>
Like this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
echo 'True';
}
Also, although it's technically allowed to not use curly brackets in the example you gave, I'd highly recommend that you use them. If you were to come back later and add some more logic for when the condition is true, you might forget to add the curly brackets and thus ruin your code.
There is in_array function.
if(in_array($a, array('are','abc','xyz','lmn'), true)){
echo 'true';
}
NOTE:
You should set the 3rd parameter to true to use the strict compare.
in_array(0, array('are','abc','xyz','lmn')) will return true, this may not what you expected.
Try this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
// Code
}
http://php.net/manual/en/function.in-array.php
in_array — Checks if a value exists in an array
bool in_array ( mixed $needle , array $haystack [, bool $strict =
FALSE ] ) Searches haystack for needle using loose comparison unless
strict is set.

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;
}

Can boolean needle be passed to in_array?

Can I pass false as a needle to in_array()?
if(in_array(false,$haystack_array)){
return '!';
}else{
return 'C';
}
The $haystack_array will contain only boolean values. The haystack represents the results of multiple write queries. I'm trying to find out if any of them returned false, and therefore not completed.
PHP won't care what you pass in as your 'needle', but you should probably also use the third (optional) parameter for in_array to make it a 'strict' comparison. 'false' in PHP will test as equal to 0, '', "", null, etc...
Yep, just like in your example code. Because in_array returns a boolean to indicate whether the search was successful (rather than returning the match), it won't cause any problems.
There's got to be a better way.
<?php
echo (in_array(false,array(true,true,true,false)) ? '!' : 'C');
echo (in_array(false,array(true,true,true,true)) ? '!' : 'C');
Output:
!C
Yes you can but why don't you do it with a single boolean variable like this:
$anyFalseResults = false;
... your query loop {
// do the query
if( $queryResult == false ) $anyFalseResults = true;
}
at the end of the loop $anyFalseResults will contain what you are looking for.

how do I say "If a string contains "x" in 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.

Check if variable has a number php

I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:
"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true
There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help.
You can use the strcspn function:
if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
echo "true";
else
echo "false";
strcspn returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.
There is no need to invoke the regular expression engine for this.
$result = preg_match("/\\d/", $yourString) > 0;
Holding on to spirit of #Martin, I found a another function that works in similar fashion.
(strpbrk($var, '0123456789')
e.g. test case
<?php
function a($var) {
return (strcspn($var, '0123456789') != strlen($var));
}
function b($var) {
return (strpbrk($var, '0123456789'));
}
$var = array("abc", "!./#()", "!./#()abc", "123", "abc123", "!./#()123", "abc !./#() 123");
foreach ($var as $v) {
echo $v . ' = ' . b($v) .'<hr />';
}
?>
This should help you:
$numberOfNumbersFound = preg_match("/[0-9]+/", $yourString);
You could get more out of the preg_match function, so have a look at its manual
you can use this pattern to test your string using regular expressions:
$isNumeric = preg_match("/\S*\d+\S*/", $string) ? true : false;

Categories