2013-12-07 48 views
1

我想從我的標題中刪除一些文本(使用wordpress)。 例子:亞歷山德拉斯坦 - Saxobeat先生 輸出:Saxobeat先生PHP:刪除第一個' - '前的所有內容

我試了很多代碼,這項工作完美的一個:

$str = "this comes before – this comes after"; 
$char = " - "; 
$strpos = strpos($str, $char); 
$str = substr($str, $strpos+strlen($char)); 
echo $str; 

但經過嘗試了很多次,得到upsed ...我看到在我的wordpress文章頁面中,當我在標題中鍵入「 - 」時,wordpress會自動將它改爲:「 - 」與正常不同(較大)的「 - 」(以另一種字體複製,您將看到區別) 。

我試圖取代 「 - 」 和 「 - 」,但輸出爲 「s下次之前 - 這是以後

謝謝!

回答

3

這就是你想更換em dash。但是,你正在尋找一個常規的短跑。先嚐試運行通過這個爛攤子的串碼和閱讀blog article我是從

編輯

一個完整的工作示例,基本上粘貼在博客文章示例代碼和固定的一個小錯誤與你substr

function scrub_bogus_chars(&$text) { 
    // First, replace UTF-8 characters. 
    $text = str_replace(
    array("\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93",  "\xe2\x80\x94", "\xe2\x80\xa6"), 
    array("'", "'", '"', '"', '-', '--', '...'), 
    $text); 

    // Next, replace their Windows-1252 equivalents. 
    $text = str_replace(
    array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)), 
    array("'", "'", '"', '"', '-', '--', '...'), 
    $text); 
} 

// Original string (with em dash) 
$text = "this comes before – this comes after"; 

// Ensure regular dashes will be available 
scrub_bogus_chars($text); 

// Lastly, extract the interesting part of the original string 
$char = ' - '; 
$strpos = strpos($text, $char); 
$text = substr($text, $strpos + strlen($char)); 
echo $text . PHP_EOL; 
+1

+1:對於實際閱讀這個問題(雖然,你的代碼看起來像ars ..我想這不能幫助)'= /' –

+0

@note這適用於常規破折號和電子短劃線。 – quickshiftin

+0

@tereško代碼大部分是剪切和粘貼的,但我只是把它清理乾淨了;) – quickshiftin

0

這不是一個正常的破折號-它是一個特殊的utf8字符。您需要在代碼中使用特殊字符。隨着explode()

$parts = explode(' – ', 'this comes before – this comes after'); 
echo $parts[1]; 

或者與preg_match()

preg_match('~\– (.*)~', 'this comes before – this comes after', $matches); 
echo $matches[1]; 
+0

或者你可以有一個更通用的解決方案,像我的,它使用常規破折號或電子短劃線。 – quickshiftin

0

這裏:

echo explode($char, $str)[1]; 
1

你應該使用爆炸:

$str = "Alexandra Stan - Mr. Saxobeat "; 
$char = " - "; 
$str = explode($char, $str); 
echo $str[1]; 

返回

Saxobeat先生

+0

這不會在他的源代碼字符串中看到em,這看起來像是真正的問題。 – quickshiftin

+0

@quickshiftin:對不起,我是法國人,我無法理解你的意思是「他的破折號」 編輯:好吧,明白了,我已發佈不要照顧這個 – user2196728

相關問題