Вопрос

I have a string, that is like the following:

$string = "New video gameSome TV showAnother item";

I want to be able to access each item individually, to get something like the following output:

New video game
Some TV show
Another item

How can I add a \n after each item name in the string or some other random character, that I can later explode into an array to access each item individually in the string?

Это было полезно?

Решение

$string = preg_replace('/([a-z])([A-Z])/', "\\1\n\\2", $string);

To answer your comment to include words that end in a closing parenthesis or a number:

$string = preg_replace('/([a-z0-9\)])([A-Z])/', "\\1\n\\2", $string);

Другие советы

We (humans) can differentiate the items and identify one from another based on what it means to us. but a computer must be given a criteria to do all that.

You need to change the way you store the string by simply adding a delimiter (comma or colon) and do not expect the computer to read our minds on this.

what about this ,

$string = "New video game/nSome TV show/nAnother item";

$string = explode("/n", $string);

print_r( $string);

This is not a good way to try to separate items. as has been said multiple time, save yourself the headache and use delimiters, That being said, this returns desied results from given string.

$my_string = "New video gameSome TV showAnother item";
preg_match_all('/[A-Z]{1}([A-Z]{2,5}|[a-z\s])+/',$my_string, $matches);
var_dump($matches);

But i'm sure you'll find more cases this doesn't work if you keep using patterns that don't make sense.

[A-Z]{1} - find one uppercase letter
()+ - next pattern one or more times
[A-Z]{2,5}|a-z\s - 2 -5  uppercase letters(for acronyms) OR lowercase letters and spaces

This does what you ask here. Good luck not breaking it.

var dump looks like - never mind the second part.

array(2) { [0]=> array(3) { [0]=> string(14) "New video game" [1]=> string(12) "Some TV show" [2]=> string(12) "Another item" } [1]=> array(3) { [0]=> string(1) "e" [1]=> string(1) "w" [2]=> string(1) "m" } } 

I do a bit comparison to efficiently look for uppercases, and I only consider uppercases past the first character that aren't preceded by another uppercase or a space.

<?php

$s = "New video gameSome TV showAnother item";
$i = 0;
$j = 0;
$phrases = array();
$cap_bit = pow(2, 5);
while($j < strlen($s))
{
    $n = ord($s{$j});

    if(($n & $cap_bit) == 0 && 
       ($j == 0 || (
            ord($s{$j - 1}) & $cap_bit) > 0 && 
            $s{$j - 1} != ' ') && 
       $j > 0)
    {
        $phrases[] = substr($s, $i, $j - $i);
        $i = $j;
    }

    $j++;
}


$phrases[] = substr($s, $i);
var_dump($phrases);

Result:

array(3) {
  [0]=>
  string(14) "New video game"
  [1]=>
  string(12) "Some TV show"
  [2]=>
  string(12) "Another item"
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top