我需要以这种方式为大字符串的每一行获取一些数据:
|
- > $ content = $ value |
- >第一部分是$ content,第二部分(如果exisiting)将是$ more |
- >中间的文字将是$ content,最后一部分将是$ more 示例
|text|
text
another|text|example
have fun|
text|more text
||
|just some keywords (25-50% )|
结果
$content = 'text'
$content = 'text'
$content = 'text'; $more = 'example'; $pre = 'another'
$content = 'have fun'
$content = 'text'; $more = 'more text'
$content = just some keywords (25-50% )'
所以我尝试使用explode和if / else来解决这个问题,但是我失败了:
$lines = explode(PHP_EOL, $content);
foreach ($lines as $key => $value) {
if ($line != "") {
$line_array = explode("|", $value);
if(count($line_array) == 3) {
// is '|anything|' or 'x|y|z'
}
else if (count($line_array) == 1) {
// anything else
}
}
}
正则表达式
我的尝试(.*)\|(.*)\|(.*)$
获取的所有行都有两个|
,而不是其他行......
答案 0 :(得分:1)
/(?:^|^([^\|]+))\|?([^\|]+)\|?(?:$|([^\|]+)$)/gm
似乎有效,请参见https://regex101.com/r/yW7oR3/6进行测试。
我的设计就像:
答案 1 :(得分:-2)
你的失败"出了什么问题?进场?这是缺少的代码...
$lines = explode(PHP_EOL, $content);
foreach ($lines as $line) {
$line = trim($line)
if ($line !== "") {
$parts = explode("|", $line);
if (count($parts)==1) {
$content = $parts[0];
} else if (count($parts)==2) {
$content = $parts[0];
$more = $parts[1];
} else if (count($parts)==3) {
$content = $parts[1];
$more = $parts[2];
} else {
echo 'Invalid - more than 2 "|"';
}
}
}
此代码遵循您对要求的英文描述。