0

我需要一个用于替换 URL 的正则表达式,如下所示:

http://www.domain.com/web/

我试过了:

$pattern = '/\bhttp\S*\/"\b/';

但不工作。

我需要一个开头和结尾的字符串,它是一个 JSON 字符串,带有

"ImgRemotePath":"http:\/\/localhost\/\/web\/images\/obj\/car.png"

或者

"ImgRemotePath":"http:\/\/localhost\/\/web\/images\/"

我需要最后删除:

"ImgRemotePath":"http:\/\/localhost\/\/web\/images\/"

"ImgRemotePath":""
4

2 回答 2

1

这应该是您正在寻找的东西:

<?php
// Subject data
$json = '"ImgRemotePath":"http://localhost/web/images/obj/car.png"';

// First procedure: Using regular expression to match and replace
/* Will match anything except '"' inside the JSON value
 * This limitation means that you should improve the regular expression, if
 * you wish to parse values that includes the '"' character, i.e. improve the
 * regular expression if this is needed, or use the alternative procedure     */
$result = preg_replace('/"ImgRemotePath":"[^"]*"/', '"ImgRemotePath":""', $json);

print $result;

/* Alternative procedure: Decoding, deleting value and encoding back to JSON */
// Convert JSON to associative array
$jsonArray = json_decode('{' . $json . '}', true);

// Set value to empty string
$jsonArray['ImgRemotePath'] = '';

// Cast/encode to JSON
$jsonString = json_encode($jsonArray);

// Remove '{' and '}'
$result = substr($jsonString, 1, strlen($jsonString) - 2);

print $result;
于 2013-10-11T09:10:32.217 回答
0
"http.*/"

试试这个模式。基本上,以“http”开头,可以有任何字符并以 / 结尾

于 2013-10-11T08:44:49.333 回答