[英]Extract text from a string that contains brackets in PHP
I have a string with State name and code like this 我有一个国家名称和代码的字符串
KT16(Ottershaw)
Now i need to extract text from ()
. 现在我需要从
()
提取文本。 I need to extract Ottershaw. 我需要提取Ottershaw。 How can i do this with php.
我怎么能用PHP做到这一点。
should be : 应该 :
preg_match('/\(([^\)]*)\)/', 'KT16(Ottershaw)', $matches);
echo $matches[1];
Just get the substring between the first opening bracket and the last closing bracket: 只需获取第一个左括号和最后一个右括号之间的子串:
$string = "KT16(Ottershaw)";
$strResult = substr($string, stripos($string, "(") +1,strrpos($string, ")") - stripos($string, "(")-1);
以下RegEx应该有效:
/\[(.*?)\]/
This is a sample code to extract all the text between '[' and ']' and store it 2 separate arrays(ie text inside parentheses in one array and text outside parentheses in another array) 这是一个示例代码,用于提取'['和']'之间的所有文本,并将其存储为2个单独的数组(即一个数组中括号内的文本和另一个数组中括号外的文本)
function extract_text($string)
{
$text_outside=array();
$text_inside=array();
$t="";
for($i=0;$i<strlen($string);$i++)
{
if($string[$i]=='[')
{
$text_outside[]=$t;
$t="";
$t1="";
$i++;
while($string[$i]!=']')
{
$t1.=$string[$i];
$i++;
}
$text_inside[] = $t1;
}
else {
if($string[$i]!=']')
$t.=$string[$i];
else {
continue;
}
}
}
if($t!="")
$text_outside[]=$t;
var_dump($text_outside);
echo "\n\n";
var_dump($text_inside);
}
Output: extract_text("hello how are you?"); 输出:extract_text(“你好,你好吗?”); will produce:
将产生:
array(1) {
[0]=>
string(18) "hello how are you?"
}
array(0) {
}
extract_text("hello [http://www.google.com/test.mp3] how are you?"); extract_text(“你好[http://www.google.com/test.mp3]你好吗?”); will produce
会产生
array(2) {
[0]=>
string(6) "hello "
[1]=>
string(13) " how are you?"
}
array(1) {
[0]=>
string(30) "http://www.google.com/test.mp3"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.