获取第n个连字符前后的文本

5

Question:

ABC-101-Description-text-1
ABC-2001-Description-text-with-more-text-2
ABC-20001-Some-more-Description-text-with-more-text-3

有人能帮我获取第n个连字符之前的所有文本吗?如果我想在一个实例中获取ABC-20001,或者想要ABC-2001后面的所有内容。

我知道我需要使用strstr或strpos,但不确定,希望得到一些帮助...


你的字符串是固定的还是会在运行时改变? - Pramod
1个回答

6
如果您已经知道下面的“n”是一个整数:
$parts = explode('-',$string,$n);

让我们来看看这个字符串:
$string = "ABC-20001-Some-more-Description-text-with-more-text-3";

如果你想要第二个连字符前的内容:
$parts = explode('-',$string,$n+1); // n=2,
$parts[0] = 'ABC-20001';
$parts[1] = 'Some-more-Description-text-with-more-text-3';

第三个例子在这里:http://uk1.php.net/manual/en/function.explode.php

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接