2014-11-03 28 views
0

我想抓住一个字符串的具体部分有一个开始字符和结束字符。抓住一个字符串的特定部分

例如;

$str = "Lorem ipsum |example xyz|dolor sit amet, consectetur adipiscing 
elit |example|. Vivamus at posuere magna. Suspendisse rutrum rhoncus leo 
vitae vehicula. Nunc nec dapibus nisi. Donec facilisis mauris sapien, eget 
blandit enim |example xyz| dignissim auctor.|example| Nullam a porta orci. 
Donec pharetra urna odio, ut pellentesque est eleifend vel. Nulla tincidunt 
tellus sed dui fermentum viverra. Vivamus sit amet semper mi." 

我想抓零件全部|example xyz| .. blabla.. |example|

我该怎么做? 谢谢..

+0

你有什么尝试,是预期的结果数组的比赛或第一场比赛? – naththedeveloper 2014-11-03 09:19:48

+0

你可以在'|'上爆炸并丢弃结果中的奇数键(因为它们总是包含'example'或'example xyz' .. – naththedeveloper 2014-11-03 09:21:17

回答

0
function stringcutout($string,$start,$stop) 
{ 
$ret=''; 
if (strstr($string,$start)) 
{ 
    $p=strpos($string,$start); 
    $b=substr($string,$p+strlen($start)); 
    if (strstr($b,$stop)) 
    { 
    $p=strpos($b,$stop); 
    $b=substr($b,0,$p); 
    $ret=$b; 
    } 
} 
return $ret; 
} 

我在用这个。我知道这是不是很漂亮,但工作...

+0

请注意,这个函数只查找字符串的第一个出现。 – 2014-11-03 09:20:27

+0

否我很好,但我想获得一个包含“| example xyz | .. blabla .. | example |”的整个部分的数组,我的结果返回一个空字符串。 – kbrk 2014-11-03 09:44:17

+0

$ start ='| example xyz | '; $停止=' |例子|'; $ RET = stringcutout($海峡,$开始,$停止); 打印($ RET); 这将返回我:悲坐阿梅德,consectetur adipiscing elit – 2014-11-03 11:22:57

0

\|([\w\s]+)\|使用正则表达式来获得|

UPDATE之间的任何话

要包括|example xyz||example|使用这个表达式:

(\|example xyz\|[\w\s]\|example\|) 
+0

我觉得他想要的部分“管道外” – naththedeveloper 2014-11-03 09:22:01

+0

其实我想整个部分。例如xyz | .. blabla .. | example |“ – kbrk 2014-11-03 09:41:31

+0

@brk我已更新回答 – Justinas 2014-11-03 12:16:43

0

如果你有一个固定的字符串,你正在寻找你可以使用preg_match

preg_match_all('/\|example xyz\|[\w\s\,\.]+\|example\|/', $str, $matches); 
if (count($matches) > 0) 
{ 
    foreach ($matches[0] as $match) 
    { 
     echo $match; 
    } 
} 
+0

它总是返回空数组。 – kbrk 2014-11-03 09:39:38

+0

那么,你能告诉我你是如何使用preg_match? – Seunhaab 2014-11-03 09:44:00

+0

检查我的新编辑,应该给你”| example xyz | text | example |“在$匹配 – Seunhaab 2014-11-03 10:00:14

0

好了,所以你需要一个不同的功能...... 你可以得到多种内容,包括任何始于|例如使用此项功能:

$return=array(); 
$ex=explode('|example',$str); 
if (sizeof($ex)>0) {unset($ex[0]); foreach ($ex as $s) {$x=strpos($s,'|'); $return[]=substr($s,$x+1);}} 

,如果你不想要的额外最后结果(这是不是“终止”的例子),你可以取消它...