2017-06-06 86 views
-1

$價值我想篩選值如何篩選在PHP

例如: 11201:12

從腳本

$duration = get_post_meta($post->ID, 'TMDB_Runtime', true); 
if (! empty($duration)) { 
echo '<div class="gmr-duration-item" property="duration">' . $duration . __(' <a class="fa fa-clock-o" aria-hidden="true"></a>','movies') . '</div>'; 

我試着使用SUBSTR和str_replace函數,並把它into function.php

<?php 
$text = '$duration'; 
$text = substr($text, 0, 3); 
echo $text =str_replace("1","01:", $text); 
?> 

但是總是顯示解析錯誤。

回答

0

你可以做這種方式,靜態:

<?php 
$duration = "112"; 
$exploded = str_split($duration); 
$exploded[0] = "0".$exploded[0].":"; 

$final = implode($exploded); 
echo $final; 
?> 
+0

謝謝老兄:)。這是真正的方法,它的工作,但是...''持續時間'它並不總是'112'值,我的意思是,從$持續時間(eee)獲得價值並將其過濾到(ee:ee) –

+0

但它會一直有1,2,3或4個數字是一個時間。所以你可以首先檢查字符串長度,然後有一個switch語句,如果它是1,2,3或4,應用0:#或#:#等等 – clearshot66

1

有兩個問題,我在此代碼段中注意到:

<?php 
$text = '$duration'; 
$text = substr($text, 0, 3); 
echo $text =str_replace("1","01:", $text); 
?> 

第一: echo $text =str_replace("1","01:", $text);是不正確的語法。您不能將函數分配給函數。將它分成兩行。

$text = str_replace("1","01:", $text); 
echo $text; 

二: $text = '$duration';不設置$text112。它將它設置爲文字字符串$duration。 PHP中的單引號不會評估變量,這就是雙引號。所以,試試這個來代替:

$text = "$duration"; 
+0

是的,我知道,在'$ duration'應該是'112'和'回聲$文字= str_replace(「1」,「01:」,$ text);'應該是'01:01:2'這只是一個例子,因爲我已經不知道 –