如何检查字符串中是否包含多个特定字符? - php

我有一个字符串,需要检查几个字符。我可以用strpos();做到这一点。但是在这种情况下,我将需要多次使用strpose();。像这样的东西:

$str = 'this is a test';
if(
   strpos($str, "-") === false &&
   strpos($str, "_") === false &&
   strpos($str, "@") === false &&
   strpos($str, "/") === false &&
   strpos($str, "'") === false &&
   strpos($str, "]") === false &&
   strpos($str, "[") === false &&
   strpos($str, "#") === false &&
   strpos($str, "&") === false &&
   strpos($str, "*") === false &&
   strpos($str, "^") === false &&
   strpos($str, "!") === false &&
   strpos($str, "?") === false &&
   strpos($str, "{") === false &&
   strpos($str, "}") === false 
  )
    { do stuff }

现在我想知道,是否可以使用regex定义我的条件摘要?

编辑:这是一些示例:

$str = 'foo'     ----I want this output---> true
$str = 'foo!'    -------------------------> false
$str = '}foo'    -------------------------> false
$str = 'foo*bar' -------------------------> false

等等。换句话说,我只需要文本字符:abcdefghi...

参考方案

使用否定的超前断言。

if (preg_match("~^(?!.*?[-_^?}{\]\[/'@*&#])~", $str) ){
// do stuff
}

仅当字符串不包含任何上述字符时,这才会在花括号内进行操作。

如果您希望字符串仅包含单词字符和空格。

if (preg_match("~^[\w\h]+$~", $str)){
// do stuff
}

要么

AS @Reizer提及,

if(preg_match("~^[^_@/'\]\[#&*^!?}{-]*$~", $str)){

如果您不想匹配一个空字符串,请用*替换上面的+(在字符类旁边)。

仅适用于字母和空格。

if(preg_match("~^[a-z\h]+$~i", $str) ){

PHP str_replace是否具有大于13个字符的限制? - php

直到击中第13个字符为止。一旦str_ireplace在cyper数组中击中“ a”,str_ireplace就停止工作。数组的大小有限制吗?请记住,如果键入“ abgf”,我会得到“ nots”,但是如果键入“ abgrf”,我应该得到“ notes”,那么我就会得到“ notrs”。机架使我的大脑无法解决。$_cypher = array("n…

php-printf和sprintf具有不同的输出 - php

我编写了以下微型php程序来测试printf和sprintf:<?php $str_1 = printf("%x%x%x", 65, 127, 245); $str_2 = sprintf("%x%x%x", 65, 127, 245); echo $str_1 . "\n"; echo $s…

PHP-MySQL结果转换为JSON - php

我试图了解如何将MySQL结果转换为JSON格式,以便以后可以在Javascript中使用此JSON来构建HTML表。但是我的代码只是产生大量的空值,我还不明白为什么。$result = mysqli_query($con, "SELECT * FROM Customers"); $test = json_encode($result);…

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

PHP:从函数返回值并直接回显它? - php

这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…