iT邦幫忙

1

請教php要怎麼樣截取出特定字元之前的字串呢

php

例如我想分析的字串是
Domain Name: google.com.tw Registrant: Google Inc.
若我想截取出 Registrant: 之前的 字串 也就是 Domain Name: google.com.tw
請問該如何做是否有相關的函式可以處理

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
6
ccutmis
iT邦高手 2 級 ‧ 2011-08-18 13:08:54

您可以試試 preg_match 函式...
例如:

<pre class="c" name="code">
<?php
$strOld='Domain Name: google.com.tw Registrant: Google Inc.';
echo '原始字串:<br />'.$strOld.'<br />';

preg_match("/(Domain Name: [^\s]*) Registrant: Google Inc./",$strOld, $matches);
echo '<br />比對後的字串:<br />'.$matches[1];
?>
4
wiseguy
iT邦超人 1 級 ‧ 2011-08-18 18:14:13

如果你這些字串內容都是固定的,那麼用一般字串處理函式 strstr() 會比用 Regular Expression 快上好幾倍。

<pre class="c" name="code">$s = 'Domain Name: google.com.tw Registrant: Google Inc.';
$r = strstr($s, ' Registrant:', true);
echo $r; // 顯示 "Domain Name: google.com.tw"

不過 strstr() 第三個參數是 php5.3.0 才支援,假如你使用 5.3.0 以前版本,則改用:

<pre class="c" name="code">$s = 'Domain Name: google.com.tw Registrant: Google Inc.';
$r = substr($s, 0, strpos($s, ' Registrant:'));
echo $r; // 顯示 "Domain Name: google.com.tw"
0
mjj2000
iT邦新手 5 級 ‧ 2012-04-14 13:20:13

preg_replace()的方式:

<pre class="c" name="code">
$s = 'Domain Name: google.com.tw Registrant: Google Inc.'; 
echo preg_replace('/ Registrant: Google Inc\.$/', '', $s);

我要發表回答

立即登入回答