我在字符串中存储了一个Instagram标题
类似于:
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
我的目标是将字符串拆分为一个包含标签的数组,并将字符串的其余部分保留在一个变量中
例如
$matches[0] --> "#beautiful"
$matches[1] --> "#photo" etc..
also $leftoverString="This is a beautiful photo";
如有任何帮助,将不胜感激
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
if (preg_match_all('/(^|'s)(#'w+)/', $caption_text, $arrHashtags) > 0) {
print_r($arrHashtags[0]);
}
$caption_text = "This is a beautiful photo #beautiful #photo #awesome #img";
preg_match_all ( '/#[^ ]+/' , $caption_text, $matches );
$tweet = preg_replace('/#([^ 'r'n't]+)/', '', $caption_text);
您可以尝试:
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
$array = explode(' ', $caption_text);
$photos = array();
foreach ($array as $a) {
if ($a[0] == '#') {
$photos[] = $a;
}
}
一种可能性是按"进行分解,然后检查每个项目是否有标记。如果没有,你可以让其他人再次成为一个字符串。例如:
$arr_text = explode(' ',"This is a beautiful photo #beautiful #photo #awesome #img");
$tmp = array();
foreach ($arr_text as $item) {
if(strpos($item,'#') === 0) {
//do something
} else {
$tmp[] = $item;
}
}
implode(' ', $tmp);
希望这能有所帮助。
<?php
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
$new = explode(" ",$caption_text);
foreach($new as $key=>$value)
{
if($value[0] == "#")
$match[] = $value;
else
$rem .= $value." ";
}
print_r($rem).PHP_EOL;
print_r($match)
?>
$temp = explode(' ', $caption_text);
$matches = array();
foreach ($temp as $element) {
if ($element[0] == '#') {
$matches[] = $element;
}
else
$leftoverstring .= ' '.$element;
}
print_r($matches);
echo $leftoverstring;
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
$matches = explode('#',$caption_text);
for($i = 0; $i<count($matches);$i++)
{
$matches[$i]= '#'.$matches[$i];
}
print_r($matches);
<?php
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
$new = explode(" #",$caption_text);
print_r($new);
?>