彰化一整天的論壇

 找回密碼
 立即註冊
查看: 872|回復: 0

PHP replace only first occurrence of a string match.

[複製鏈接]
發表於 2012-10-11 21:43:00 | 顯示全部樓層 |閱讀模式
How to replace only the first occurrence of a string in php.

Say you wanted to only replace the first occurrence of a string match instead of all occurrences You would use php preg_replace function to do the trick.
The code is below:

<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $var, 1); // outputs '123def abcdef abcdef'
?>
Just incase you wanted to still match all occurrences, just use the php function erag_replace.
The code is below:

<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string
echo ereg_replace('abc', '123', $var); // outputs '123def 123def 123def'
?>
source: http://newsourcemedia.com/blog/php-replace-only-first-occurrence-of-a-string-match/
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

 ㄚ母滴雞湯
 員林香純滴雞精

Archiver|手機版|小黑屋|彰化一整天的論壇(Excel,Office)  |网站地图

GMT+8, 2019-9-21 17:45 , Processed in 0.118944 second(s), 21 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表