如果您嘗試更改腹部到<a href="/glossary/a/abdomen">abdomen</a>
這裏有一個建議:
$terms = 'abdomen|etc|parental care';
// this is the string of the terms separated by pipes
$terms = explode('|',$terms);
// split terms into an array (aka $terms)
foreach ($terms as $key => $value) {
$terms[$key] = preg_replace('/\s\s*/',' ',strtolower($value));
}
// change each into lowercase and normalize spaces
$str = 'Here\'s some example sentence using abdomen. Abdomen is a funny word and parental care is important.';
foreach ($terms as $term) {
// this will loop all the terms so it may take a while
// this looks like a requirement because you have multi-word terms in your list
$str = preg_replace('/\b('.$term.')\b/i', '<a href="/glossary/'.$term{0}.'/'.str_replace(' ','%20',$term).'">$1</a>', $str);
// regardless of case the link is assigned the lowercase version of the term.
// spaces are replaced by %20's
// --------------------
// ------- EDIT -------
// --------------------
// added \b's around the term in regex to prevent, e.g.
// 'etc' in 'ketchup' from being caught.
}
編輯:檢查的最新留言中的代碼。
將更新代碼。我剛剛看到了多詞詞彙。 – inhan 2012-02-16 21:42:47
現在更新它。 – inhan 2012-02-16 22:05:08
這是另一種方法,但這個代碼的問題在於,當您更改'a'標籤的href時,您必須重新編碼preg-replace,而不是使其不是特定於html的那麼多。 – dyoser 2012-02-16 23:44:55