douchuitang0331
douchuitang0331
2018-07-17 16:06

解析基于字符串搜索和重构的字符串

  • php

I am trying to reconstruct a string based off defined elements found it it. Each element that is found, I need to get the text related to it until the next heading is found. Below I have added some code to help explain better. Any direction/help is appreciated.

//defined headings to search on
$search_items ='Summary:,Education:,Experience:,Other:,Qualifications/Requirements:';

$string = 'Summary: It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Education:Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like.Other:Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.';

$headers = explode(',', $search_items);

foreach ($headers as $heading) {
    $substring = substr($string, strpos(utf8_encode($string), utf8_encode($heading)) + 1);   
    if ($substring  !== false) {
       echo "<p><strong>$heading</strong></p><p></p>";
    }
} 

With the code above, I can find all the headings and wrap them in the strong tag. Then $substring contains all the remaining of the text after the heading. The problem is that I only want the text until the next heading is found so I can drop it in the empty p tags.

so using the string above it would look something like:

Summary:

It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Education:

Various versions have evolved over the years, sometimes by accident, sometimes on purpose injected humour and the like.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐