Php strpos special characters
I am using PHP Version 5.1.6
I have a string (session file) and need to extract a value from it, so I am looking for a needle in the string, but it returns false, I minified the code to this:
$string = ';SERVER_NAME|s:17:"stackoverflow.com";REMOTE_ADDR|s:13:"69.59.196.211";';
$start = strpos($string, ';SERVER_NAME|s:"');
echo $start; // prints nothing because $start = false
$start = strpos($string, 'SERVER_NAME|s:');
echo $start; // prints 1;
As you noticed, if I have a ';' or the character "" in the needle, search returns false, I tried to use chr () for all characters in the needle, but had the same result. If I remove the ';' and '' 'from the string if it finds a needle in the string.
How can I search for special characters in a string using PHP?
a source to share
You're looking for ;SERVER_NAME|s:"
one that is clearly missing from the haystack. I think you wanted to use it ;SERVER_NAME|s:17:"
like a needle.
$start = strpos($string, ';SERVER_NAME|s:17:"');
echo $start; // prints 0
It was a typo that I missed, sorry, problem resolved. Correct code:
$result = ';SERVER_NAME|s:17:"stackoverflow.com";REMOTE_ADDR|s:13:"69.59.196.211";';
$str_start = ';SERVER_NAME|s:';
$str_end = ':"';
$start = strpos($result, $str_start)+strlen($str_start);
$end = strpos($result, $str_end, $start);
$len = $end - $start;
$str_len = substr($result, $start, $len);
echo $server_name = substr($result, ($end + strlen($str_end)), $str_len);
and at the end it prints: stackoverflow.com
This is how it works, thanks everyone for the help!
a source to share
I would say that you think this is a lie, because the position of the line might be 0
that evaluates to FALSE
(assuming you are using the needle that is present in the line). You should always compare with ===
.
From the documentation (big red warning block):
Attention
This function can return Boolean
FALSE
, but it can also return a non-boolean value that evaluates toFALSE
, for example,0
or""
. Please read the section on Booleans for more information. Use a statement===
to test the return value of this function.
It works great for me with "
. The first echo does not output anything because the substring ;SERVER_NAME|s:"
is not really contained in the original string.
a source to share
I got a problem with strpos where I started a single quote string and looked for a string that contains a double quote.
Example 1 - Doesn't work:
strpos($text,'class="level')
Explanation: The double quote (") ends the line for some reason, even if we started the line with a single quote (').
Example 2 - Doesn't work:
strpos($text,'class=\"level')
Explanation: There is a escape character before the double quote ("), but it does not perform this function.
Example 3 - Works !!:
strpos($text,"class=\"level")
Explanation: If you start the needle with a double quote, you can avoid the double quote with a backslash ().
Hope this helps ...
a source to share