我正在尝试使用PHP进行检查。我想要的是检查:
我已经写过这段代码(最后if语句是我真正想要的)来检查这个但是没有得到我想要的结果:
$str = "dfgdfg]";
if($str[0] != '[') {
echo "FIRST NOT EQUAL TO";
}
if(substr($str,-1) != ']') {
echo "SECOND NOT EQUAL TO";
}
if( ($str[0] != '[') && (substr($str,-1) != ']') ) {
echo "COND MET!";
}
如果我运行此代码,我认为最后一个if语句会执行,但只执行第一个if语句。最后一个if语句中的逻辑有什么问题?
答案 0 :(得分:1)
您将最后一个语句设置为“AND - &&”并且应该是“OR - ||”
if( ($str[0] != '[') || (substr($str,-1) != ']') ) {
echo "COND MET!";
}
答案 1 :(得分:0)
您的最终[
语句检查字符串的第一个字符是不 a ]
,最后一个字符也是不一个]
。如果您从$str
中删除了最后一个COND MET
,则会看到if( ($str[0] != '[') && (substr($str,-1) != ']') ) {
echo "COND MET!";
}
输出。
[
如果您希望检查以确保字符串分别以]
和if( ($str[0] == '[') && (substr($str,-1) == ']') ) {
echo "COND MET!";
}
开头和结尾,则需要:
public class Replacements
{
private String[] search; // sorted in descending length and order, eg: sch, ch, c
private String[] replace; // corresponding replacement
Replacements(String[] s, String[] r)
{
if (s.length != r.length)
throw new IllegalArgumentException();
final TreeMap<String, String> map = new TreeMap<String, String>(Collections.reverseOrder());
for (int i = 0; i < s.length; i++)
map.put(s[i], r[i]);
this.search = map.keySet().toArray(new String[map.size()]);
this.replace = map.values().toArray(new String[map.size()]);
}
public String replace(String input)
{
final StringBuilder result = new StringBuilder();
// start of yet-to-be-copied substring
int s = 0;
SEARCH:
for (int i = s; i < input.length(); i++)
{
for (int p = 0; p < this.search.length; p++)
{
if (input.regionMatches(i, this.search[p], 0, this.search[p].length()))
{
// append buffer and replacement
result.append(input, s, i).append(this.replace[p]);
// skip beyond current match and reset buffer
i += this.search[p].length();
s = i--;
continue SEARCH;
}
}
}
if (s == 0) // no matches? no changes!
return input;
// append remaining buffer
return result.append(input, s, input.length()).toString();
}
}
答案 2 :(得分:0)
简单的RegExr检查怎么样:
if (preg_match('/^\[.*\]$/', $str) {}