简体   繁体   English

PHP preg_match()或strpos检查字符串是否以子字符串开头

[英]PHP preg_match() or strpos to check if string starts with substring

I am changing views of a page depending the $_GET['code'] it can equal a series of different codes but they will all start with either Red , Town or Bearing , then a series of characters. 我根据$_GET['code']来更改页面的视图,该页面可以等于一系列不同的代码,但它们都将以RedTownBearing开头,然后是一系列字符。

For example, the following would all trigger the condition 例如,以下所有条件都会触发

RedWings-223123-NY
Townmansion-2341322-KY
BearingWays-23422-DC

I have tried 我努力了

<?php if(preg_match("%(?=.*Bear)(?=.*Red)(?=.*Town)%", $_GET['code'])): ?>

   <span> new view </span>

<?php endif ?>

and

<?php if( strpos($_GET['code']), "Red" ) !== false) || strpos($_GET['code']), "Bear" ) !== false || strpos($_GET['code']), "Town" ) !== false)): ?>

   <span>new view</span>

<?php endif ?>

Your strpos is incorrect syntactically, you close the functions before passing the term to search for. 您的strpos在语法上是不正确的,您在传递术语以进行搜索之前关闭了函数。

Your regex requires all terms be present and doesn't check for the start of the string. 您的正则表达式要求所有条件都存在,并且不检查字符串的开头。 You need to use an or and a leading anchor. 您需要使用or和前导锚。 This: 这个:

^(?:Bear|Town|Red)

should do it. 应该这样做。

Regex Demo: https://regex101.com/r/civdig/3/ 正则表达式演示: https : //regex101.com/r/civdig/3/

Correct strpos usage: 正确的strpos用法:

<?php if( strpos($_GET['code'], "Red" ) === 0 || strpos($_GET['code'], "Bear" ) === 0 || strpos($_GET['code'], "Town" === 0)): ?>

   <span>new view</span>

<?php endif ?>

You need the 0 to confirm it matches, otherwise you are checking that it is somewhere in there. 您需要使用0来确认它是否匹配,否则您要检查它是否在其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM