猿问

在 php 中使用 trim 我想使用两个条件或一组条件来修剪?

这是我想要实现的想法


$foo = $data['string']; 

$bar = trim(preg_replace($patterns, $replacements, $data['string']), "_" || "-"); 

echo $bar;

我试图达到的结果:


示例_示例


或者


举例说明


在某些情况下,我使用preg_replace()的场景可能以“_”或“-”结尾。在这种情况下,我想使用trim()删除它。显然,情况是将这些字符保留在字符串中:


Example_example_ 到 Example_example


或者


示例-示例-到示例-示例


12345678_0001
浏览 176回答 3
3回答

HUWWW

"_" || "-"is的值TRUE,因为 PHP 逻辑运算符总是返回一个布尔值,并且这两个字符串都是真值。第二个参数 totrim()必须是一个字符串,并TRUE转换为 string "1",因此您正在从字符串中修剪该字符。to 的第二个参数trim()应该只是一个包含要从末尾删除的所有字符的字符串,而不是带有||.$bar = trim(preg_replace($patterns, $replacements, $data['string']), "_-");

HUH函数

试试这个正则表达式:(-|_)(?:^|\s)$re = '/(-|_)(?:^|\s)/m';$str = 'The is test-test_ and Test_test- and the end';$str = preg_replace($re,'',$str);echo $str;会输出:是test-testand test_testand end

喵喵时光机

将要修剪的字符作为第二个参数提供给trim():$string = 'Example_example_';echo trim($string, '_-'); //Example_example
随时随地看视频慕课网APP
我要回答