第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

在 PHP 中替換字符串的特定部分

在 PHP 中替換字符串的特定部分

PHP
慕桂英546537 2022-12-30 16:56:35
我有一個(gè)看起來像這樣的字符串:$string = '[some_block title="any text" aaa="something" desc="anytext" bbb="something else"]';我需要替換 title= 和 desc= 引號(hào)之間的文本title 和 desc 的順序可以改變,這意味著 desc 可以在 title 之前,或者也可以有其他的東西,比如 aaa= 或 bbb= before/inbetween/after。我不能使用 str_replace 因?yàn)槲也恢酪?hào)之間會(huì)出現(xiàn)什么文本。我在想一個(gè)可能的解決方案是我可以在 title= 上展開,然后在雙引號(hào)上展開,然后將它與新文本拼湊起來,并重復(fù) desc=只是想知道是否有更好的解決方案,我不知道做這樣的事情?
查看完整描述

2 回答

?
aluckdog

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊

使用 regexp php 函數(shù)preg_replace,您可以將搜索模式和替換傳遞添加為兩個(gè)數(shù)組:


$string = preg_replace([

      '/ title="[^"]+"/',

      '/ desc="[^"]+"/',

   ], [

      sprintf(' title="%s"', 'replacement'),

      sprintf(' desc="%s"', 'replacement'),

   ], $string);


    // NOTE: Space was added in front of title= and desc= 

    // EXAMPLE: If you do not have a space, then it will replace the text in the quotes for title="text-will-get-replaced" as well as something similar like enable_title="text-will-get-replaced-as-well". Adding the space will only match title= but not enable_title=



查看完整回答
反對(duì) 回復(fù) 2022-12-30
?
滄海一幻覺

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊

出于興趣和比較的目的,我將我的原始功能作為“如何不這樣做”的示例發(fā)布。


我建議使用 preg_replace 而不是 Pavel Musil 的答案:


<?php


$string = '[some_block title="any text" aaa="something" desc="anytext" bbb="something else"]';


$new_string = replaceSpecial('title=', '"', 'my new text', $string);


echo $new_string; // will output: [some_block title="my new text" aaa="something" desc="anytext" bbb="something else"]


function replaceSpecial($needle, $text_wrapper, $new_text, $haystack) {

    $new_string = $haystack;

    $needle_arr = explode($needle, $haystack, 2);

    if (count($needle_arr) > 1) {

        $wrapper_arr = explode($text_wrapper, $needle_arr[1], 3);

        $needle_arr[1] = $wrapper_arr[0].$needle.'"'.$new_text.'"'.$wrapper_arr[2];

        $new_string = $needle_arr[0].$needle_arr[1];

    }

return $new_string;

}


?>


查看完整回答
反對(duì) 回復(fù) 2022-12-30
  • 2 回答
  • 0 關(guān)注
  • 146 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)