【问题标题】:Trim string until specified character and also trim suffix修剪字符串直到指定字符并修剪后缀
【发布时间】:2015-01-19 14:13:06
【问题描述】:

我不知道这是否可以使用 trim、substr 或 explode。 我所拥有的是一个打印这种类型的字符串的回声(它实际上是一个面包屑)

Choose > Apples > Green > Wholesale > 5KG boxes

是否可以将字符串截断以使其仅打印

Apples > Green 

面包屑的结构是固定的,所以我总是想切掉第一部分(Choose >)和最后两部分(> Wholesale > 5KG boxes),所以我需要切掉所有东西,直到第一个“>”字符以及第三个“>”字符之后的所有内容,包括字符。

【问题讨论】:

  • 分解>上的字符串,然后从结果数组中连接你想要的元素。

标签: php string explode trim substr


【解决方案1】:

你可以使用preg_replace函数。

$string = "Choose > Apples > Green > Wholesale > 5KG boxes";
echo preg_replace('~^[^>]*>\s*|\s*(?:>[^>]*){2}$~', '', $string);

输出:

Apples > Green

【讨论】:

  • 好的,我找到了问题所在,我必须将$stringParts = explode(' > ', $string); 更改为$stringParts = explode(' > ', $string);,现在它可以工作了。如何在 preg_replace 中使用 > ?我必须逃避它对吗?现在它什么都不做,很可能我必须使用替代>
  • 是的,$ 是正则表达式中的特殊字符。你必须要逃避它。
【解决方案2】:

解决此问题的最简单方法是将字符串分解为数组。之后,您只需打印您需要的两个项目。

$string = 'Choose > Apples > Green > Wholesale > 5KG boxes';
$stringParts = explode(' > ', $string);
$newString = $stringParts[1].' > '.$stringParts[2];

【讨论】:

  • 嗯,由于某种原因,如果我输入包含如下字符的字符串,则会出现“未定义偏移量:”错误Apples > Package (E030) [AX/1982 - BX/1992] > 5KG (1596grams/100pcs) [AX/1987 - BX/1991] (red) boxed > Expire date > 10.16.2018 我使用上面的代码创建了一个函数
  • 这就是我的工作方式$string = 'Choose > Apples > Green > Wholesale > 5KG boxes'; $stringParts = explode(' > ', $string); $newString = $stringParts[1].' > '.$stringParts[2];
【解决方案3】:
$separator = ' > ';
$string = "Choose > Apples > Green > Wholesale > 5KG boxes";
//explode your string, but keep in mind someone could use > in the content
$parts = explode($separator, $string);

//unset the first
array_shift($parts);
array_pop($parts); //unset the last one
array_pop($parts); //unset the second last

//combine them back thogether
$output = implode($separator, $parts);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多