php - 如何检查字符串是否仅包含特定字符

标签 php preg-match

我需要检查一个字符串以确定它是否包含 | 以外的任何字符,以便为那些除了 | 之外什么都没有的变量分配 NULL 值(理论上可以有任意数量的 | 字符,但可能不会超过 5-6 个)。喜欢||||

我可以看到循环遍历字符串的每个字符或类似的东西,但我觉得必须有更简单的方法。

最佳答案

if (preg_match('/[^|]/', $string)) {
    // string contains characters other than |
}

或:

if (strlen(str_replace('|', '', $string)) > 0) {
    // string contains characters other than |
}

关于php - 如何检查字符串是否仅包含特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10248107/

相关文章:

php - 使 Javascript 成为一项要求

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

javascript - 如何在回显 div 的 php echo 上引用 javascript 函数

php - 正则表达式提取javascript方法调用

PHP替换图像src并从包含不同html标签的字符串在图像标签中添加新属性

php preg_match 以关键字开头

php - PHP Documentor 中的注释关联数组

php - 具有动态页面 (php) 性能的 apache .htaccess 规则

PHP preg_match : a pattern which satisfies all MySQL field names (including 'table.field' formations)

php preg_match 帮助从 URL 获取 facebook 用户名/id