使用两个定界符展开字符串并遍历结果

问题描述 投票:1回答:1

经过本网站搜索两天后,我找不到解决我要求的正确方法,请指导我。另外,对不起我的英语。

我有一个字符串,其中可能包含在字符串中不同位置插入的几对定界符,例如:

[快速的[开始]棕狐[端]跳过[开始]懒[结束]的狗。

[开始]那只棕色[结束]的狐狸跳过了[开始]懒[结束]的狗。

我需要什么:每次我找到那些定界符时,我都希望在pdf的两列中显示定界的内容,而且还要在这些定界符之前和之后保留其余的字符串。

假设上面有第一个例子,我需要得到以下结果:

快速$ mpdf-> SetColumns(2);褐狐$ mpdf-> SetColumns(0);跳过$ mpdf-> SetColumns(2);懒人$ mpdf-> SetColumns(0);狗

这是我从php.net使用的功能,但是如您所见,它仅适用于一对定界符,我不知道如何在此处使用foreach并保持所需的格式:

    function multiexplode ($delimiters,$string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$exploded = multiexplode(array('[begin]','[end]'),$mystring);

//if delimiters exist, then split in two columns only those parts of the string
if (count($exploded) > 1) {

//begining of the string
$mpdf->WriteHTML($exploded[0]);

//split in two columns
$mpdf->SetColumns(2);
$mpdf->WriteHTML($exploded[1]);

//reset to single column and write the rest of the string
$mpdf->SetColumns(0);
$mpdf->WriteHTML($exploded[2]);

} else {
//set two columns for the entire string
$mpdf->SetColumns(2);
$mpdf->WriteHTML($mystring);
}

谢谢

php explode mpdf
1个回答
0
投票

签出preg_split。它类似于explode,但您可以使用正则表达式作为分隔符。

https://www.php.net/manual/en/function.preg-split.php

这里是一个示例,通过使用[begin]或[end]作为分隔符:https://3v4l.org/nlC9K

© www.soinside.com 2019 - 2024. All rights reserved.