我想问一下,是否可以在特定关键字之间获取一些字符串?例如,我有两个这样的句子:
I will go to #new bathroom and wash the car#
结果:bathroom and wash the car
Someone need an #new icebreaker# to hold that problem
结果:icebreaker
我想条件让#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;
?>
我的问题是我无法找到追逐最后一个标签的方法
答案 0 :(得分:1)
与正则表达式不同的另一种方法是explode字符串和replace句子中的new
如果您在句子#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
)
*/
答案 1 :(得分:1)
我已经为您的问题编写了以下代码,但请记住我自己还是初学者。 它完全符合您的要求,但我确信有更好的解决方案。
<?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;
?>
希望这有助于:)
答案 2 :(得分:1)
使用此正则表达式:
/#new (.+)#/i
与preg_match()
一起,您将获得数组中的匹配项:
<?php
$string = "Someone need an #new icebreaker# to hold that problem";
preg_match("/#new (.+)#/i", $string, $matches);
var_dump($matches[1]); // icebreaker
如果您预计会有多个匹配项,请使用preg_match_all()
获取所有匹配项。
答案 3 :(得分:0)
您可以使用正则表达式来匹配它。这是一个链接和一个简单的正则表达式。
(#)\w+(#)
(\#)+(.)+(\#)
答案 4 :(得分:0)
您可以搜索&#34;#&#34;从结束, 比如$ end = strpos($ sentence,&#34;#&#34;,-0);
然后获得你已经拥有的子串。
$new = substr($sentence, $start, $end);