PHP7擴充開發之字串處理

來源:互聯網
上載者:User

標籤:

本文和大家分享的主要是PHP7擴充開發中字串的處理相關知識,希望通過本文的分享能協助大家更好的學習php 。

這次,我們來看看字串在PHP擴充裡面如何處理。

範例程式碼如下:

<?phpfunction str_concat($prefix, $string) {

$len = strlen($prefix);

$substr = substr($string, 0, $len);

if ($substr != $prefix) {

return $prefix." ".$string;

} else {

return $string;

}

}

echo str_concat("hello", "word");echo "\n";echo str_concat("hello", "hello bo56.com");echo "\n";?>

上面的str_concat方法實現了如下功能:

1、當字串不包含指定前置詞字元串時,把前置詞字元串和被檢測字元合并返回。

2、當字串包含指定前置詞字元串時,原樣返回。

我們將使用PHP擴充的方式實現str_concat功能。

代碼

實現str_concat方法

str_concat方法的PHP擴充源碼:

PHP_FUNCTION(str_concat)

{

zend_string *prefix, *subject, *result;

zval *string;

if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz", &prefix, &string) == FAILURE) {

return;

}

subject = zval_get_string(string);

if (zend_binary_strncmp(ZSTR_VAL(prefix), ZSTR_LEN(prefix), ZSTR_VAL(subject), ZSTR_LEN(subject), ZSTR_LEN(prefix)) == 0) {

RETURN_STR(subject);

}

result = strpprintf(0, "%s %s", ZSTR_VAL(prefix), ZSTR_VAL(subject));

RETURN_STR(result);

}

代碼說明

zend_string是PHP7新增的結構。結構如下:

struct _zend_string {

zend_refcounted_h gc; /*gc資訊*/

zend_ulong h; /* hash value */

size_t len; /*字串長度*/

char val[1]; /*字串起始地址*/

};

在 Zend/zend_string.h 提供了一些zend_string處理的一些方法。

ZSTR_ 開頭的宏方法是zend_string結構專屬的方法。主要有如下幾個:

#define ZSTR_VAL(zstr) (zstr)->val

#define ZSTR_LEN(zstr) (zstr)->len

#define ZSTR_H(zstr) (zstr)->h

#define ZSTR_HASH(zstr) zend_string_hash_val(zstr)

ZSTR_VAL ZSTR_LEN ZSTR_H 宏方法分別對應zend_string結構的成員。 ZSTR_HASH是擷取字串的hash值,如果不存在,就調用hash函數產生一個。

代碼中故意把第二個參數轉換成zval。主要是為了展現zend為我們提供了一些列的操作方法。如,zval_get_string, zend_binary_strncmp。

這些方法在 Zend/zend_operators.h 檔案中。

 

來源:博學無憂

PHP7擴充開發之字串處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.