Find the occurrence of backslash in a string

老子叫甜甜 提交于 2019-12-04 05:32:46

问题


If my string is : aud\ios, how do i check it out for the presence of \ in it?

I tried using preg_match('\\' , $string) but it does not work. What's the correct way to achieve this?


回答1:


For something simple as this, you don't need a regular expression. A string function like strpos() should be enough:

if (strpos('aud\ios', '\\') !== FALSE) {
    // String contains '\'
}

Note that you need to escape the backslash here. If you simply write \, then PHP considers it as an escape sequence and tries to escape the character that follows. To avoid this, you need to escape the escape using another backslash: \\.

As for matching a literal backslash using a preg_* function, you'll need to use \\\\ instead of a single \.

From the PHP manual documentation on Escape Sequences:

Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

So your code would look like:

preg_match('/\\\\/', $string); // Don't use this though

where:

  • / - starting delimiter
  • \\\\ - matches a single literal \
  • / - ending delimiter

For additional information about this, see:

  • How to properly escape a backslash to match a literal backslash in single-quoted and double-quoted PHP regex patterns



回答2:


if (strstr('aud\ios', '\\') !== false) {
    //Contains "\"
}



回答3:


I use this function a lot, you can easily check if a string contains

function StringContains($the_string,$contains)
{
    return strpos($the_string, $contains) !== FALSE;
}   

check it out: http://3v4l.org/LrDBd

of course you have to escape the backslash when calling the function like this StringContains('aud\ios','\\');



来源:https://stackoverflow.com/questions/22691720/find-the-occurrence-of-backslash-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!