我是PHP的新手,我需要根据值而不是字符数将字符串分割成特定的部分。
我听说过explode函数和子字符串,但我不知道如何使用它来实现我想要的。
我得到了一个输出字符串:
Name: example Email: e.g@example.com Website: http://examples.com/ Comment: this is where the comment goes, we can't use explode because there's lots of spaces here Another comment: this is another comment Some random info: this is more info...
为了美观起见,我想在单独的行中显示此信息。
有没有办法在一个特定的单词之后但在另一个特定的单词之前返回一个单词?
发布于 2014-02-18 23:42:49
您可以使用正则表达式来实现这一点,前提是给定的字符串始终是正则格式的。
使用preg_split()可能构成了基础:
$arr = preg_split('/(?=[A-Z])/', $str, -1, PREG_SPLIT_NO_EMPTY);正则表达式使用positive lookahead断言在任何大写字母之前的位置拆分给定的字符串。
如果我们在阵列上执行print_r(),您可以看到以下输出:
Array
(
[0] => Name: example
[1] => Email: e.g@example.com
[2] => Website: http://examples.com/
[3] => Comment: this is where the comment goes ...
[4] => Another comment: this is another comment
[5] => Some random info: this is more info...
)首先,你是如何获得这个字符串的?如果这是您控制范围内的事情,那么我强烈建议使用JSON或类似的方法来传输数据。它更简单,错误更少--而且你可以确定它是有效的。
发布于 2014-02-18 23:42:50
这是可行的-
$regex = "/[A-Z][^A-Z]*?\:\s.*?(?(?=[A-Z][^A-Z]*?\:)|$)/";
$string = "Name: Example Email: e.g@example.com Website: http://examples.com/ Comment: this is where the comment goes, we can't use explode Because there's Lots of spaces here Another comment: this is another comment Some random info: this is more info";
if(preg_match_all($regex, $string, $matches)){
var_dump($matches[0]);
}
/*
OUTPUT
array
0 => string 'Name: Example ' (length=14)
1 => string 'Email: e.g@example.com ' (length=23)
2 => string 'Website: http://examples.com/ ' (length=30)
3 => string 'Comment: this is where the comment goes, we can't use explode Because there's Lots of spaces here ' (length=98)
4 => string 'Another comment: this is another comment ' (length=41)
5 => string 'Some random info: this is more info' (length=35)
*/发布于 2014-02-18 23:18:15
使用像这样的简单字符串操作函数,让你的生活变得简单。
<?php
$strx='Name: example Email: user@example.com Website: http://example.com/';
$str=stristr($strx,"Comment :",true);// Take all chars before 'Comments :'
$str= str_replace(": ",":",str);
$str = str_replace(" ","\n");
echo $str . '\n Comment : '. ; // Its
echo stristr($strx,"Comment :"); // Done
?>https://stackoverflow.com/questions/21857863
复制相似问题