當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP quotemeta()用法及代碼示例

quotemeta()函數是PHP中的內置函數,它接受字符串作為參數並返回一個字符串,該字符串在字符串中的某些預定義字符之前添加了反斜杠。

預定義的字符是:

  • 句點(。)
  • 反斜杠(\)
  • 加號(+)
  • 星號(*)
  • 問號(?)
  • 括號([])
  • 脫字號(^)
  • 美元符號($)
  • 括號(())

用法:


 quotemeta($string)

參數:此函數僅接受一個必填參數$string。此參數指定要在上述預定義字符前麵添加反斜杠的字符串。

返回值:它通過在$string參數中的預定義字符之前添加反斜杠來返回字符串。

例子:

Input:  $str = "geek$ for geeks?"
Output: geek\$ for geeks\?

Input: $str = "+geek* for geeks."
Output: \+geek\* for geeks\.

以下示例程序旨在說明PHP中的quotemeta()函數:

程序1:當字符串包含“?”和“ $”預定義字符時

<?php 
// PHP program to demonstrate the  
// working of quotemeta() function  
  
$str = "geek$ for geeks?"; 
  
// prints the string by adding backslashes  
// in front of the predefined characters 
// '$' and '?' 
echo(quotemeta($str)); 
?>

輸出:

geek\$ for geeks\?

程序2:當字符串具有“ *”,“。”和“ +”預定義字符時

<?php 
// PHP program to demonstrate the  
// working of quotemeta() function  
  
$str = "+geek* for geeks."; 
  
// prints the string by adding backslashes  
// in front of the predefined characters 
echo(quotemeta($str)); 
?>

輸出:

\+geek\* for geeks\.

程序3:當字符串的方括號和括號為預定義字符時。

<?php 
// PHP program to demonstrate the  
// working of quotemeta() function  
  
$str = "[]geek for geeks()"; 
  
// prints the string by adding backslashes  
// in front of the predefined characters 
// brackets and parenthesis 
echo(quotemeta($str)); 
?>

輸出:

\[\]geek for geeks\(\)

程序4:當字符串的尖號(^)作為預定義字符時。

<?php 
// PHP program to demonstrate the  
// working of quotemeta() function  
  
$str = "2 ^ 2 = 4"; 
  
// prints the string by adding backslashes  
// in front of the predefined characters 
// caret (^) 
echo(quotemeta($str)); 
?>

輸出:

2 \^ 2 = 4

參考:
http://php.net/manual/en/function.quotemeta.php



相關用法


注:本文由純淨天空篩選整理自ChetnaAgarwal大神的英文原創作品 PHP | quotemeta() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。