在PHP中从字符串的开头删除“a”,“an”和“the”的最佳方法是什么?
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?
我正在创建一种通过标题的第一个字母过滤一组博客文章的方法。 唯一的麻烦是我当然要在标题开头之前从标题的开头删除“A”,“An”和“The”。 这就是我现在正在做的事情: p>
$ 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;
code> pre>
这很好用,但看起来很笨重。 有没有更好的方法呢? p>
div>
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