PHP获取特定单词中的字符串
我想问一下,有没有可能在一个指定的关键字之间得到一些字符串?例如,我有两个这样的句子:PHP获取特定单词中的字符串,php,Php,我想问一下,有没有可能在一个指定的关键字之间得到一些字符串?例如,我有两个这样的句子: I will go to #new bathroom and wash the car# 结果:浴室和洗车 Someone need an #new icebreaker# to hold that problem 结果:破冰船 我想设置条件以获取#new# 你知道怎么做吗 到目前为止,我的代码是: <?php $sentence = "I will go to #new bathroom and
I will go to #new bathroom and wash the car#
结果:浴室和洗车
Someone need an #new icebreaker# to hold that problem
结果:破冰船
我想设置条件以获取#new#
你知道怎么做吗
到目前为止,我的代码是:
<?php
$sentence = "I will go to #new bathroom and wash the car#";
$start = strpos($sentence, "#new");
//$end = strpos($sentence, "#");
$end = 20; //because my strpos still wrong, I define a static number
$new = substr($sentence, $start, $end);
echo $new;
?>
我的问题是我找不到追踪最后一个标签的方法,你可以使用正则表达式来匹配它。这里是一个链接和一个简单的正则表达式
(#)\w+(#)
(\\\\)+()+(\\\\\)
与正则表达式不同的另一种方法是对字符串和句子中的新
如果句子#new
$string = "I will go to #new bathroom and wash the car#";
$string1 = "Someone need an #new icebreaker# to hold that problem";
function getString($string, $delimiter = '#')
{
$string_array = explode($delimiter, $string);
return str_replace('new ', '', $string_array[1]);
}
echo getString($string);
//bathroom and wash the car
echo getString($string1);
//icebreaker
我想更多的工作与阵列
$string = [
"I will go to #new bathroom and wash the car#",
"Someone need an #new icebreaker# to hold that problem"
];
function getString($string, $delimiter = '#')
{
$result = [];
foreach ($string as $value) {
$string_array = strstr($value, $delimiter) ? explode($delimiter, $value) : [];
$result[] = isset($string_array[1]) ? str_replace('new ', '', $string_array[1]) : NULL;
}
return $result;
}
print_r(getString($string));
/*
Array
(
[0] => bathroom and wash the car
[1] => icebreaker
)
*/
您可以从末尾搜索“#”,
比如$end=strpos($句子,“#”,-0)
而不是像你已经有的那样得到子字符串
$new = substr($sentence, $start, $end);
我已经为您的问题编写了以下代码,但请记住我自己还是一个初学者。
这正是你想要的,但我相信有更好的解决办法
<?php
$string = "I will go to #new bathroom and wash the car#";
$stringArray = str_split($string);
$output = '';
$count = 0;
foreach($stringArray as $letter){
if($count == 0 && $letter == '#'){
$count = 1;
} elseif($count == 1){
if($letter != '#'){
$output .= $letter;
} else {
$count = 2;
}
}
}
echo $output;
?>
希望这有帮助:)使用此正则表达式:
/#new (.+)#/i
与一起,您将获得阵列中的匹配项:
<?php
$string = "Someone need an #new icebreaker# to hold that problem";
preg_match("/#new (.+)#/i", $string, $matches);
var_dump($matches[1]); // icebreaker
检查确保$string
中有一个$delimiter
,否则explode()
将无法工作,您将收到一个未定义的索引通知。此外,当没有新的时,它仍然会得到两个shebang之间的内容。最后,当有奇数个shebang时,它会变得混乱。@ishegg在第二段中,我为未定义的索引通知提供了一个解决方案…关于散列标签的奇数…OP说他有句子…我试图为他在问题中出现的特定案例提供其他不同于常规经验的方式当然,我同意这是更好的方法!正则表达式应该始终是最后一个选项,因为它们更昂贵。虽然在这种情况下,另一种方法似乎更复杂。很抱歉问一下,这个解决方案比ishegg解决方案更快/更轻吗?在使用strpos之前,我尝试按空格分隔符将句子分解为数组,但对程序来说似乎太重了IMO@EmilioGort好啊谢谢你的回答,我也会保留这个答案,以备下次开发。非常感谢你!我尝试了你的正则表达式,使用preg_匹配,结果只有“1”(数字1)