可以告诉如何删除字符后?在PHP中。我有一个字符串测试?= new我需要从字符串中删除字符以及=。
答案 0 :(得分:24)
最短的一个:
echo strtok('test?=new', '?');
如果您想保留问号,解决方案几乎相同:
echo strtok('test?=new', '?').'?';
答案 1 :(得分:3)
此解决方案使用简单的正则表达式删除?
字符及其后面的所有字符。
$string = "test?p=new";
$new_string = preg_replace("/\?.+/", "", $string);
答案 2 :(得分:2)
为什么不:
$pos = strpos($str, '?'); // ? position
$str = substr($str, 0, $pos);
答案 3 :(得分:2)
你可以用写得很好的正则表达式做到这一点,但更简单快捷的方法就是在“?”上爆炸字符串。字符,并使用结果数组中的第一个元素。
$str = "test?=new";
$str2 = explode("?", $str);
$use_this = $str2[0];
$ use_this [0]将是“test”。如果要添加“?”回来,只是连接:
$use_this = $use_this."?";
答案 4 :(得分:2)
您也可以尝试使用preg_replace()
:
$string = 'test?q=new';
$result = preg_replace("/\?.+/", "", $string);
如果出于某种原因,您希望将?
保留在结果中......您也可以这样做:
$string = 'test?q=new';
$result = preg_replace("/\?.+/", "?", $string);
(或者,您可以使用正面的后视断言,如@ BlueJ774建议的那样),像这样:
$result = preg_replace("/(?<=\?).+/", "", $string);
但理想情况下,以及将来参考,如果您正在使用查询字符串,您可能希望在某些地方使用parse_str 点,像这样:
$string = 'test?q=new';
parse_str($string, $output);
因为这将为您提供一个数组(在本例中为$output
),可以使用该数组来处理查询字符串的所有部分,如下所示:
Array
(
[test?q] => new
)
但通常......你可能只想在这一点上使用查询字符串...所以输出更像是这样:
Array
(
[q] => new
)
答案 5 :(得分:1)
这是单行:
$s = strpos($s, '?') !== FALSE ? strtok($s, '?') : $s;
您可以通过以下命令行对其进行测试:
php -r '$s = "123?456"; $s = strpos($s, "?") !== FALSE ? strtok($s, "?") : $s; echo $s;'
答案 6 :(得分:0)
substr
和strpos
最简单的方法是使用substr()
DOCs和strpos()
DOCs。
$string = 'test?=new';
$cut_position = strpos($string, '?') + 1; // remove the +1 if you don't want the ? included
$string = substr($string, 0, $cut_position);
正如您所看到的,substr()
通过索引从字符串中提取子字符串,strpos()
返回其搜索的字符的第一个实例的索引(在本例中为?
})。
答案 7 :(得分:0)
使用strstr功能。
<?php
$myString = "test?=new";
$result = strstr($myString, '=', true);
echo $result ;
第三个参数true
告诉函数在第一次出现第二个参数之前返回所有内容。