2012-03-26 12 views
0

文字列の特定の部分を返そうとしています。私はsubstrを見ましたが、私はそれが私が探しているものだとは思わない。この文字列を使用して文字列の一部を返す

/text-goes-here/more-text-here/even-more-text-here/possibly-more-here 

は、どのように私は最初の2 //すなわちtext-goes-here

おかげで、

答えて

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/
+0

私は 'explode'は配列ではなく文字列を返すと考えました。今や意味をなさない!ありがとう! –

+0

mr manualは "文字列パラメータを区切り文字で区切られた境界に分割して作成した文字列を返します。" –

+0

しばらくの間は 'explode'を見ていません。もう一度読む。 :) –

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 
?> 
0

確かに動作し、上記の方法を爆発間のすべてを返すことができます。 2番目の要素のマッチングの理由は、空白の要素が配列内に挿入されるとき、あるいは空白の要素が何もせずに区切り文字で開始されるときに空白要素を挿入するからです。一部は名前のキャプチャグループに一致するように指示します...

<?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 <一致>あなたはPに<試合>一部を省略した場合、あなたは?:もう1つの可能な解決策は、正規表現を使用することです。? 「[1] $試合で一致する部分で終わるでしょ$マッチ[0]前方に一部が含まれています 『/テキストは-行く-ここで/』のようにスラッシュ

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) 
関連する問題