我需要以这种方式为大字符串的每一行获取一些数据:
- 空行应忽略
- 如果没有
|
-> $content = $value - 如果有一个
|
->第一部分将是$content,第二部分(如果存在)将是$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% )'
所以我试着用explosion和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
}
}
}
正则表达式我的尝试(.*)'|(.*)'|(.*)$
得到有两个|
的所有行,但不是其他行…
/(?:^|^([^'|]+))'|?([^'|]+)'|?(?:$|([^'|]+)$)/gm
似乎可以工作,
参见https://regex101.com/r/yW7oR3/6进行测试。
我是这样设计的:
- $1 = $pre
- $2 = $content
- $3 = $more
你的"失败"方法出了什么问题?这里是缺失的代码…
$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 "|"';
}
}
}
此代码遵循你方英文需求描述。