Tag:php
Article From:https://segmentfault.com/q/1010000012145176
Question:
<?php
$newword = "
Direct: lead toLittle: big";$str_txt = "this is a path leading to a beautiful hall. ">

Requirements: use PHP code to achieve “direct” replacement of “direct” in the article, and replace “small” in the article with “big”. The variable $newword is submitted by a multiline text box with a set of replacement text per row.

Answer 0:
<?php
$newword = "
Direct: lead toLittle: big";$newword = explode (PHP_EOL, trim ($newword));$patter = $need = array ();Foreach ($newworD as $key => $value) {$tmp = explode (':', $value);$patter[] ='/'.$tmp[0].'/';$need[] = $tmp[1];}$str_txt = "this is a path leading to a beautiful hall. ";Echo preg_replace ($patter, $need, $str_txt);

Answer 1:

The method used is clumsy.

<?php
$newword = "
Direct: lead toLittle: big";$str_txt = "this is a path leading to a beautiful hall. ";Split up according to a newline$keyword_list = trim ($newword);$keyword_arr =Explode ("\n", $keyword_list);Build a replacement array$replace_arr = [];$temp = [];Foreach ($keyword_arr as $k = & &)Gt; $v) {Divide into a replacement array$temp = explode (':', $v);$replace_arr[$temp[0]] = $temp[1];}BeReplace textForeach ($replace_arr as $k => $v) {$str_txt = str_replace ($k, $v, $str_txt);}Var_dumP ($str_txt);

The running output is as follows:

# fhy at Centos7 in ~/myphp [14:55:16]
→ php replace.php 
string(42) "This is a road to the beautiful hall. "(venv)

Answer 2:

1 <?php
2 $newword = “
3 Direct: lead to
4 Little: big
5 “;
6 $str_txt = “This is a path to the beautiful hall. “;
7 $pairs = preg_split(“/[:”.PHP_EOL.”]/”, trim($newword));
8 $i = 0;
9 while($i < count($pairs)) {
10 list($ori[], $tar[]) = [$pairs[$i++], $pairs[$i++]];
11 }
12 var_dump(str_replace($ori, $tar, $str_txt));
Output:
string(42) “This is a road to the beautiful hall. “
str_replaceIt supports batch replacement.

Leave a Reply

Your email address will not be published. Required fields are marked *