dreamevil0002 2010-05-12 12:53
浏览 195
已采纳

php strpos特殊字符

I'm using PHP Version 5.1.6

I have a string (session file) and need to extract a value from it, so i'm searching for a needle in the string but it returns false, I reduced 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 the character ';' or the character '"' in the needle, the search returns false, I tryed to use chr() for all characters in the needle but had the same result, If I remove the ';' and the '"' from the string if finds the needle in the string.

How can I search special characters in a string using PHP ?

  • 写回答

4条回答 默认 最新

  • duanpuluan0480 2010-05-12 12:59
    关注

    You are searching for ;SERVER_NAME|s:" which clearly is not present in the haystack. I guess you meant to use ;SERVER_NAME|s:17:" as the needle.

    $start = strpos($string, ';SERVER_NAME|s:17:"');
    echo $start; // prints 0
    

    It was a typo that i missed, sorry problem solved. The correct code is:

    $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

    So it works, thank you all for help !

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题