Someone
Someone

Reputation: 117

Removing text from Foreach iteration

Currently, I have the following code.

foreach($html->find('ol.tracklist li.track') as $element) {
   print $element->plaintext;
   print '<br>';
}

Which returns something that looks like this.

Can't Use My Phone (Suite) 3:34
Hi 0:35
Cel U Lar Device 6:28
Phone Down 3:29
U Use To Call Me 1:13
Mr. Telephone Man 3:12

I am wondering how I can remove the numbers at each of these results. I am assuming I have to use regex to achieve this, but after messing with regex a bit, I was unable to find a way to achieve this without affecting the titles that also contain things like. : or other symbols.

Upvotes: 1

Views: 103

Answers (6)

yariv_kohn
yariv_kohn

Reputation: 92

You should try this regex /\d+:\d+$/gm.

  • \d+ will match 1 digit or more.
  • : will match literal char of ':'.
  • $ will search the above pattern at the end of the line.
  • g will continue to search for each line on each line (w/o it you will return after the first match)
  • m will enable multi line search, which mean that the search will refer the $ at the end of each line (w/o it it will search at the end of the text only)

Good luck

Upvotes: 2

digitalway
digitalway

Reputation: 71

If it's always the same format hh:mm you can find the last space with strrpos()

$string = 'Cel U Lar Device 6:28';
$string = substr($string, 0, strrpos($string, ' '));

Upvotes: 1

Ivica Pesovski
Ivica Pesovski

Reputation: 847

You can just cut the last character of each string as long as it is either a number or a colon:

foreach($html->find('ol.tracklist li.track') as $element) {
    $text = $element->plaintext;

    while(preg_match('/[\d:]$/', $text[strlen($text)-1])) {
        $text = substr($text, 0, strlen($text)-1);
    }

    echo $text;
    print '<br>';
}

PHP DEMO

Upvotes: 2

Nick
Nick

Reputation: 147206

You could use preg_replace, using a regex to match the pattern you have at the end, and replace that with an empty string:

print preg_replace('/\d+:\d+\s*$/`, '', $element->plaintext);

Regex demo

PHP Demo

Upvotes: 3

Joseph
Joseph

Reputation: 6269

try this one it may help you, change $str variable with your text

$re = '/\d+:\d+/m';
$str = 'Caint Use My Phone (Suite) 3:34';

echo preg_replace($re, '', $str);

Upvotes: 3

Slimez
Slimez

Reputation: 607

Probably not the best solution but, you could just cut off the last 4-5 characters in the string

substr( $string, 0, -5 );

Upvotes: -2

Related Questions