I have an array of data I'm iterating through containing a Title and a Description. Each description currently begins with the corresponding title, so I want to ltrim() it off. Unfortunately, not all Titles were written in the same case format as used at the beginning of the description. I was going to use:
ltrim($description,$title)
but the case problem has stopped that.
Data EG:
array(
array("title" => "Hello World", "description" => "Hello World This is a description"),
array("title" => "Hellow world", "description" => "Hellow World This is a description"),
array("title" => "Hello again", "description" => "HELLO AGAIN This is a description"));
ltrim($description,$title) would clean the first, but leave the others alone.
I didn't create the data I'm cleaning up btw, I've just taken over the job.
Anyway, ltrim() is case-sensitive (yes?) so I'm at abit of a loss as to how to go about this. Is there any other way of doing this?
edit
Forgot to mention, the Title DOESN'T ALWAYS appear in the description, just 90% of the time
ltrim is not the function you want in the first place. The second argument to ltrim is a charlist, so it will keep removing from the left of the string as long as one of the characters is encountered.
If every title is in every description you could use str_ireplace. And replace the title with nothing, and set the count to 1.
The better alternative is to use regular expressions.
preg_replace('/^'.preg_quote($title, '/').'\s*/i', '', $description);
This will replace the title if it is the first thing in the description, followed by any whitespace (so spaces/newlines will be removed if they come after the title. preg_quote is important to protect the regular expression incase the title contains any regex characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With