I'm creating a way to filter a set of blog posts by the first letter of the title. The only trouble is that I, of course, want to remove 'A ', 'An ' and 'The ' from the beginning of the titles before I select them by letter. Here's what I'm doing now:
$title = strtolower( $_POST['post_title'] );
$title = substr($title, 0, 2) == 'a ' ? substr($title, 2) : $title;
$title = substr($title, 0, 3) == 'an ' ? substr($title, 3) : $title;
$title = substr($title, 0, 4) == 'the ' ? substr($title, 4) : $title;
That works fine, but it seems pretty clunky. Is there a better way to go about it?
You can do this kind of thing pretty robustly with str_replace
:
$title = "A is what this title starts with";
$splitTitle = explode(" ", $title);
$blacklist = array("an","a","the");
$splitTitle[0] = str_replace($blacklist,"",strtolower($splitTitle[0]));
$revisedTitle = implode(" ", $splitTitle);
echo $revisedTitle
This will replace only the string found before the first space. It splits the string with explode
, removes the first fragment if it contains a member of $blacklist
using str_replace
, then rejoins the string with implode
.
Result:
is what this title starts with
This should work -
preg_replace('/^((the|an|a)\s)/i','',$title);
try
$vowels = array("a", "an", "the");
$title= str_replace($vowels, "", $title);
for more info :- http://in3.php.net/str_replace