0

I've been working on a code and finally got to the pint that it works but my PHP processes so much that I was wondering if there are any easier ways to fix my problem

The database I'm working with is filled with tracks from artists, and example from the table:

  • composer_name = [@123:artist_display_name1] ft. [@58:artist_display_name2]
  • track_title = Le Example ( [@798:artist_display_name3] Remix)

Where the number between the [ : is the artist_id (linked to artist profile) and the string between : ] is the display name for the artist (Sometimes artists use different names, that's why)

Now question is how to get the display names as fast as possible without brackets, but use the artist_id to perform another action (such as making a link out of it and put the artist_id in a database or something)

5
  • can you add more columns to your table to store artist_id and display_name? Commented Sep 9, 2014 at 20:59
  • I can, but with a lot of other tables involved it's basically making things to difficult Commented Sep 9, 2014 at 21:00
  • Can you make your question a bit more precise? Are you looking for DB optimization tips? Ways to parse the composer name and track title? It's difficult to know what you're looking for. Commented Sep 9, 2014 at 21:00
  • A php script to parse all the display names out of the string Commented Sep 9, 2014 at 21:01
  • So you want [@123:artist_display_name1] ft. [@58:artist_display_name2] become 'artist_display_name1 ft. artist_display_name2'? Commented Sep 9, 2014 at 21:04

1 Answer 1

1

The obligatory way would be to use a regex with preg_match:

function renderRow($rawRow) {
    return preg_replace("/\[@([0-9]*):([^\]]*)\]/", "$2", $rawRow);
}

Another way which is about 10x to 20x times faster (according to my quick benchmarks) is a more direct approach (O(N)):

function renderRow($rawRow) {
    $len = strlen($rawRow);
    $status = 0;
    for ($i = 0; $i < $len; $i++) {
        $char = $rawRow[$i];
        if ($char === '[')
            $status = 1;
        else if ($status === 1) {
            if ($char === ':')
                $status = 2;
            continue;
        }
        else if ($status === 2 && $char === ']')
            $status = 0;
        else 
            $row .= $char;
    }
    return $row;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks @KeVin, worked like a charm, exactly what I needed and way faster! Used the second function by the way! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.