如果字符串以这些字符结尾,那么

时间:2015-12-30 17:38:57

标签: php

我有以下字符串示例:

$text = 'Hello world. '; // true
$text = 'Hello world? '; // true
$text = 'Hello world! '; // true
$text = 'Hello world.   '; // true
$text = 'Hello world.'; // true

$text = 'Hello world '; // false
$text = 'Hello world'; // false
$text = 'Hello world-'; // false

如果字符串以.?!结尾,则返回true,否则返回false。

最好的方法是什么?

4 个答案:

答案 0 :(得分:2)

假设您正在询问如何测试字符串的最后一个字符,您可以使用substr()

你可以这样写一个if语句:

<?php
// Test if the last character in the string is '!'.
if (substr($text, -1) === '!') {
    return true;
}

如果要删除字符串末尾的空格,可以先使用$text = trim($text)

如果要测试所有示例,可以将in_array()与包含要测试的所有字符的数组一起使用。

if (in_array(substr(trim($text), -1), array('!', '.', '?', )) {
    return true;
}

答案 1 :(得分:1)

您可以使用rtrimstrpos$result = strpos("!?.", substr(rtrim($text), -1)) !== false; ,例如:

$result

如您所示,这会将public static class MyModel { public static Order Order { get; set; } public static void NewOrder() { Order = new Order(); } } public class Order { public Order() { Products = new List<Product>(); } public List<Product> Products { get; set; } public void AddProduct(Product product) { Products.Add(product); } } public class Product { public string Name { get; set; } public decimal Price { get; set; } } 设置为 true false

答案 2 :(得分:1)

这应该这样做:

if(preg_match('/[.?!]\h*$/', $string)){
      echo 'true';
} else {
     echo 'false';
}

这是一个字符类[],允许其中一个字符。 $是字符串的结尾。 \h*是符号后面和字符串结尾之前的任意数量的水平空格。如果您想要允许新行使用\s*

Regex101演示:https://regex101.com/r/yS3fQ6/1

PHP演示:https://eval.in/495500

答案 3 :(得分:0)

使用preg_match查找那些特殊的字符串结尾。

$text = array();
$text[] = 'Hello world. '; // true
$text[] = 'Hello world? '; // true
$text[] = 'Hello world! '; // true
$text[] = 'Hello world.   '; // true
$text[] = 'Hello world.'; // true

$text[] = 'Hello world '; // false
$text[] = 'Hello world'; // false
$text[] = 'Hello world-'; // false

foreach($text as $t) {
  echo "'" . $t . "' " . (hasSpecialEnding($t) ? 'true' : 'false') . "\n";
}

function hasSpecialEnding($text) {
  return preg_match('/(\?|\.|!)[ ]*$/',$text);
}

输出:

'Hello world. ' true
'Hello world? ' true
'Hello world! ' true
'Hello world.   ' true
'Hello world.' true
'Hello world ' false
'Hello world' false
'Hello world-' false

您可以在此处查看代码:http://sandbox.onlinephpfunctions.com/code/51d839a523b940b4b4d9440cc7011e3f2f635852