简体   繁体   中英

PHP Split sentance into words based on capital letters

I use datafeeds for products on my site and I have a problem with the way in which they are formatted. I'm trying to put a snippet together to sort this for me.

Here's how the feed currently appears: "This is one of the product description. Here are the featuresThat i need to extractBut how i need help"

What I need to do is to take the string and make it appear like this:

This is the product description.

  • Here are the features
  • That i need to extract
  • But i need help

What I have done it find the last instance of the full stop (after "description"). I have then split the new string where capital letters appear and added it to a list.

Here's the code I have at the minute but it's not working and I'm struggling with how to sort it. Please can you help?

$x = "This is one of the product description. Here are the featuresThat i need to extractBut how i need help"

$pos = strrpos($x, '.')+1;
$x = substr($x, $pos). '.';

preg_match_all('/[A-Z][^A-Z]*/', $x, $pieces);

$x = print "<ul>";

foreach($pieces as $piece) {
    $x .= print "<li>";
    $x .= $piece;
    $x .= print "</li>";
}

$x = print "</ul>";

return $x;

Use preg_split

$x = "This is one of the product description. Here are the featuresThat i need to extractBut how i need help";

$pos    = strrpos($x, '.')+1;
$x      = trim( substr($x, $pos). '.' );
$pieces = preg_split('/(?=[A-Z])/', $x, -1, PREG_SPLIT_NO_EMPTY);

$y = "<ul>";

foreach($pieces as $piece) {
    $y .= "<li>";
    $y .= $piece;
    $y .= "</li>";
}

$y .= "</ul>";

return $y;

You can use a single regex to extract these 3 sentences:

$x = "This is one of the product description. Here are the featuresThat i need to extractBut how i need help";
preg_match_all('/^.+\.\h*(*SKIP)(*F)|([A-Z].*?)(?=[A-Z]|$)/', $x, $m);

print_r($m[1]);
Array
(
    [0] => Here are the features
    [1] => That i need to extract
    [2] => But how i need help
)

Or to format them in <ul><li> use:

$y = "<ul>\n";
foreach($m[1] as $item) $y .= "<li>$item</li>\n";
$y .= "</ul>";
echo $y;

<ul>
<li>Here are the features</li>
<li>That i need to extract</li>
<li>But how i need help</li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM