使用PHP如何测试字符串的模式,然后对其进行更改?
在PHP中,给定以下字符串:使用PHP如何测试字符串的模式,然后对其进行更改?,php,regex,Php,Regex,在PHP中,给定以下字符串: $string = '/sometext?123#abc/moretext'; 我如何测试模式“?123#abc/”是否存在,该模式将始终用“?”和“/”括起来,但具有可能包括任何文本和符号的不同内部文本?模式之外的文本也将不同。我需要这样做: if ($string includes pattern ?*/) { //load the inner value into a variable //then remove the entire patern
$string = '/sometext?123#abc/moretext';
我如何测试模式“?123#abc/”是否存在,该模式将始终用“?”和“/”括起来,但具有可能包括任何文本和符号的不同内部文本?模式之外的文本也将不同。我需要这样做:
if ($string includes pattern ?*/) {
//load the inner value into a variable
//then remove the entire patern including the leading "?" and trailing "/" and replace with a single "/"
}
我该怎么做?试试这个
$s = '/sometext?123#abc/moretext';
$matches = array();
$t = preg_match('#\?(.*?)\/#s', $s, $matches);
if($matches[1])
echo "match";
else
echo "not";
输出
--输出:--
~/php\u程序$php 1.php
123#abc
/sometext/moretext
您已经回答了自己的问题:使用正则表达式。如果您不想使用正则表达式,strpos可以让您第一次出现子字符串。。用于alter Use javascript:谢谢!这起作用了。我很好奇。。。是$matches=array();需要零件吗?另外,我可以测试$t,对吗?@Inator Yes$matches=array()代码>是必需的。:)@YogeshSuthar,为什么要使用$
作为正则表达式分隔符?“这对我来说真是个坏主意。”阿兰摩尔谢谢你的指点。事实上,我只是在测试。如果你认为这是个坏主意,我会把它改成?
。我已经看到了很多以$
为分隔符的答案,所以我也使用了它。你能指出其中一些答案吗?$
和?
都是regex元字符;如果将它们用作分隔符,则不能将其用作元字符。
match
<?php
$string = '/sometext?123#abc/moretext';
$pattern = '/\\?(.*?)\\//';
if( $pieces = preg_split($pattern, $string, Null, PREG_SPLIT_DELIM_CAPTURE)) {
echo($pieces[1] . "\n");
unset($pieces[1]);
echo(implode("/", $pieces) . "\n");
}
?>
--output:--
~/php_programs$ php 1.php
123#abc
/sometext/moretext