亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

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

2 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

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


$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=



查看完整回答
反對 回復 2022-12-30
?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

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


我建議使用 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;

}


?>


查看完整回答
反對 回復 2022-12-30
  • 2 回答
  • 0 關注
  • 132 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號