替换字符串中间的文本

时间:2016-01-21 06:13:47

标签: php mysql

<table border="1">
  <tr>
    <th>id</th>
     <th>filepath</th>
   </tr>
  <tr>
    <th>1</th>
     <th>uploads/1233/a.jpg</th>
   </tr>
  <tr>
    <th>2</th>
     <th>uploads/1213/b.jpg</th>
   </tr>
  <tr>
    <th>3</th>
     <th>uploads/1243/c.jpg</th>
   </tr>
  <tr>
    <th>4</th>
     <th>uploads/1234/d.jpg</th>
   </tr>
  <tr>
    <th>5</th>
     <th>uploads/1273/e.jpg</th>
  </tr>
</table>

idfilepath来自mysql表。 我想替换uploads文件夹和图像名称之间的数值。

我如何在mysql或php中执行此操作?

2 个答案:

答案 0 :(得分:1)

试试这个例子:

<?php
$str = "uploads/1234/d.jpg";
$strArray = explode("/", $str);
$strOutput = $strArray[0]."/".$strArray[2];
echo $strOutput;
?>

在mysql中,您可以尝试这样的事情:

DELIMITER $$

CREATE FUNCTION customise_str(str_input varchar) RETURNS VARCHAR(100)
    DETERMINISTIC
BEGIN
  DECLARE COUNT INT DEFAULT 9;

  WHILE COUNT > 0 DO
SET str_input = REPLACE(str_input, COUNT, "");
    SET COUNT = COUNT - 1;
  END WHILE;

RETURN (str_input);
END  $$
DELIMITER ;;


update table_name set fielname = customise_str(fielname);

我没有尝试过这段代码。

如果您不知道如何创建存储函数,这些链接可能对您有所帮助:

http://www.mysqltutorial.org/mysql-stored-function/

https://dev.mysql.com/doc/refman/5.7/en/while.html

答案 1 :(得分:1)

试试这个preg_replace函数PHP。

$filepath = "uploads/1233/a.jpg";
echo preg_replace('/(?<=\/)[1-9][0-9]*?(?=\/)/', "replacement_string_for_the_numeric_value", $filepath);