簡體   English   中英

當第一個字符串以PHP中的特定字符串開頭和結尾時,用另一個字符串替換

[英]Replace a string, with another, when the first starts and ends with specific string in PHP

我在PHP中有一些類似於"abc167828xyz"字符串,其中中間的數字是隨機生成的。 現在,我想將每個以"abc"開頭並以"xyz"結尾的字符串替換為另一個。 請記住,數字是隨機生成的!

不是重復的。 我想替換字符串,而不是查找文件。 抱歉,我是PHP新手

碼:

<?php
$string1 = "hey abcdef abc266299xyz xyzxyz there";
echo str_replace(array("hey", "abcdef", "xyzxyz", "there"), "replaced", $string1);

我想將abc266299xyz包含到數組中,並像其他數組一樣替換它。 結果應該被replaced replaced replaced replaced replaced PS這是一個例子,不是我的真實代碼

您可以使用正則表達式/abc\\d+xyz/ ,其中\\d+表示一個或多個數字。

$re = '/(abc\d+xyz|hey|abcdef|xyzxyz|there)/';
$str = 'lorem abc167828xyz ipsum abc167828xyz dolores';
$subst = 'AnotherString';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

/(abc\\d+xyz|hey|abcdef|xyzxyz|there)/將匹配任何以豎線分隔的值,並替換為您的真實字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM