Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用正则表达式提取字符串?_Php_Regex - Fatal编程技术网

Php 如何使用正则表达式提取字符串?

Php 如何使用正则表达式提取字符串?,php,regex,Php,Regex,$str=((test:'object1',test2:'object2',test3:'object3')) 从上面的字符串中,我想提取单词object1 所以,我写了下面的代码,但它不起作用 <?php echo preg_replace("/^(.+)test:(.+)'(.+)'(.+)$/", "$3", $str); ?> 您只需使用以下正则表达式: .*?test:\s*'(.+?)'.* 你的例子是: $str = "(( test: 'object1',

$str=((test:'object1',test2:'object2',test3:'object3'))

从上面的字符串中,我想提取单词
object1

所以,我写了下面的代码,但它不起作用

<?php
  echo preg_replace("/^(.+)test:(.+)'(.+)'(.+)$/", "$3", $str);
?>

您只需使用以下正则表达式:

.*?test:\s*'(.+?)'.*
你的例子是:

$str = "(( test:   'object1',   test2:  'object2',    test3:   'object3' ))";
echo preg_replace("/.*?test:\s*'(.+?)'.*/", "$1", $str); //: object1

/^(+++)test:(++)(++)(++)$/
@AvinashRaj It return**object1',test2:'object2',test3:'object3**:(您是否将匹配的代码替换为
$3
?@YouHoGeon,您想用某物替换
object1
word,或者获取
test
键的值?因此$1将获取第一个object1,如果我将其写入$2,则获取第二个object2。是这样的还是怎样的。不,此正则表达式仅适用于键
test:
。如果您想的话捕获
'object2'
,您将用这个正则表达式替换正则表达式:
*?test2:\s*'(.+?)*。