我试图返回字符串的某个部分。我看过substr
,但我不相信这是我正在寻找的。 p>
使用此字符串:
/text-goes-here/more-text-here/even-more-text-here/possibly-more-here
如何返回前两个//
之间的所有内容,即text-goes-here
谢谢,
答案 0 :(得分:4)
$str="/text-goes-here/more-text-here/even-more-text-here/possibly-more-here";
$x=explode('/',$str);
echo $x[1];
print_r($x);// to see all the string split by /
答案 1 :(得分:1)
<?php
$String = '/text-goes-here/more-text-here/even-more-text-here/possibly-more-here';
$SplitUrl = explode('/', $String);
# First element
echo $SplitUrl[1]; // text-goes-here
# You can also use array_shift but need twice
$Split = array_shift($SplitUrl);
$Split = array_shift($SplitUrl);
echo $Split; // text-goes-here
?>
答案 2 :(得分:0)
上面的爆炸方法肯定有用。在第二个元素上匹配的原因是PHP在数组中插入空白元素,无论何时开始或在没有任何其他内容的情况下运行到分隔符。另一种可能的解决方案是使用正则表达式:
<?php
$str="/text-goes-here/more-text-here/even-more-text-here/possibly-more-here";
preg_match('#/(?P<match>[^/]+)/#', $str, $matches);
echo $matches['match'];
(?P&lt; match&gt; ...部分告诉它与命名的捕获组匹配。如果省略?P&lt; match&gt;部分,你最终会得到$ matches中的匹配部分[1] ]。$ matches [0]将包含带有正斜杠的部分,如“/ text-goes-here /".
答案 3 :(得分:0)
只需使用preg_match:
preg_match('@/([^/]+)/@', $string, $match);
$firstSegment = $match[1]; // "text-goes-here"
,其中
@ - start of regex (can be any caracter)
/ - a litteral /
( - beginning of a capturing group
[^/] - anything that isn't a litteral /
+ - one or more (more than one litteral /)
) - end of capturing group
/ - a litteral /
@ - end of regex (must match first character of the regex)