PHP/Laravel trim 命名空间中除最后一个字外的所有内容
PHP/Laravel trim all but last word in a namespace
正在尝试 trim 一个完全限定的命名空间,以便只使用最后一个词。示例命名空间是 App\Models\FruitTypes\Apple
,其中最后一个词可以是任意数量的水果类型。这不应该...
$fruitName = 'App\Models\FruitTypes\Apple';
trim($fruitName, "App\Models\FruitTypes\");
...成功了吗?它返回一个空字符串。如果我尝试 trim 只是 App\Models\
它 returns FruitTypes\Apples
正如预期的那样。我知道反斜杠是一个转义字符,但加倍应该将它们视为实际的反斜杠。
preg_match()
使用正则表达式模式 \([[:alpha:]]*)$
应该可以解决问题。
$trimmed = preg_match('/\([[:alpha:]]*)$/', $fruitName);
您的结果将保存在“$trimmed1”中。如果你不介意模式不太明确,你可以这样做:
preg_match('/([[:alpha:]]*)$/', $fruitName, $trimmed);
然后您的结果将在 $trimmed[0]
。
If matches
is provided, then it is filled with the results of search. $matches[0]
will contain the text that matched the full pattern, $matches[1]
will have the text that matched the first captured parenthesized subpattern, and so on.
preg_match - php.net
(matches
是我命名为 $trimmed
的第三个参数,完整解释请参阅文档)
正则表达式模式的解释
\
按字面意思匹配字符 \
以建立匹配的开始。
括号 ()
创建一个捕获组 return 匹配项或匹配项的子字符串。
在捕获组中([[:alpha:]]*)
:
[:alpha:]
匹配字母字符 [a-zA-Z]
*
量词表示匹配零次和无限次,越多越好
然后 $
断言字符串末尾的位置。
所以基本上,"Find the last \
then return all letter between this and the end of the string".
如果您想为此使用本机功能而不是字符串操作,那么 ReflectionClass::getShortName
将完成这项工作:
$reflection = new ReflectionClass('App\Models\FruitTypes\Apple');
echo $reflection->getShortName();
Apple
正在尝试 trim 一个完全限定的命名空间,以便只使用最后一个词。示例命名空间是 App\Models\FruitTypes\Apple
,其中最后一个词可以是任意数量的水果类型。这不应该...
$fruitName = 'App\Models\FruitTypes\Apple';
trim($fruitName, "App\Models\FruitTypes\");
...成功了吗?它返回一个空字符串。如果我尝试 trim 只是 App\Models\
它 returns FruitTypes\Apples
正如预期的那样。我知道反斜杠是一个转义字符,但加倍应该将它们视为实际的反斜杠。
preg_match()
使用正则表达式模式 \([[:alpha:]]*)$
应该可以解决问题。
$trimmed = preg_match('/\([[:alpha:]]*)$/', $fruitName);
您的结果将保存在“$trimmed1”中。如果你不介意模式不太明确,你可以这样做:
preg_match('/([[:alpha:]]*)$/', $fruitName, $trimmed);
然后您的结果将在 $trimmed[0]
。
If
matches
is provided, then it is filled with the results of search.$matches[0]
will contain the text that matched the full pattern,$matches[1]
will have the text that matched the first captured parenthesized subpattern, and so on.
preg_match - php.net
(matches
是我命名为 $trimmed
的第三个参数,完整解释请参阅文档)
正则表达式模式的解释
\
按字面意思匹配字符 \
以建立匹配的开始。
括号 ()
创建一个捕获组 return 匹配项或匹配项的子字符串。
在捕获组中([[:alpha:]]*)
:
[:alpha:]
匹配字母字符 [a-zA-Z]
*
量词表示匹配零次和无限次,越多越好
然后 $
断言字符串末尾的位置。
所以基本上,"Find the last \
then return all letter between this and the end of the string".
如果您想为此使用本机功能而不是字符串操作,那么 ReflectionClass::getShortName
将完成这项工作:
$reflection = new ReflectionClass('App\Models\FruitTypes\Apple');
echo $reflection->getShortName();
Apple