Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.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 - Fatal编程技术网

Php 如何替换字符串中选定的指针

Php 如何替换字符串中选定的指针,php,Php,我有字符串:“[a,b]一些文本[b,a]和更多” 我还有一个名为$c的值,如果它等于1,我需要像这样显示字符串: “a一些文本b和一些更多”(选择[x,y](x)的第一部分) 我尝试用str_replace来实现这一点,但似乎不起作用 能否提供解决方案?您可以使用$c变量更改调用preg\u replace的替换字符串,例如: $string = "[a,b] some text [b,a] and some more"; $c = 1; echo preg_replace('/\[([^,]

我有字符串:
“[a,b]一些文本[b,a]和更多”

我还有一个名为
$c
的值,如果它等于
1
,我需要像这样显示字符串:
“a一些文本b和一些更多”
(选择[x,y](x)的第一部分)

我尝试用
str_replace
来实现这一点,但似乎不起作用


能否提供解决方案?

您可以使用
$c
变量更改调用
preg\u replace
的替换字符串,例如:

$string = "[a,b] some text [b,a] and some more";
$c = 1;
echo preg_replace('/\[([^,]+),([^]]+)\]/', $c ? '$1' : '$2', $string) . "\n";
$c = 0;
echo preg_replace('/\[([^,]+),([^]]+)\]/', $c ? '$1' : '$2', $string) . "\n";
正则表达式查找一个
[
,后面是一些非
字符(组1),一个
,然后是一些非
]
字符(组2)和一个
]
。根据
$c
的值,匹配的文本将替换为第1组或第2组

输出:

a some text b and some more 
b some text a and some more

我在一个子字符串中使用它,您也可以在您的案例中使用此解决方案。

我认为这是preg\u replace的工作。您能建议如何做吗?您对此的使用案例是什么?还是课程/家庭作业?@JonStirling对于我的项目,我正在编写一个函数,以按人的性别显示文本。然后使用单个占位符,并用字符串替换占位符。不要在字符串中使用自定义变量选项:P