1

我已将 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";

任何帮助将不胜感激

4

8 回答 8

5
$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]);
}
于 2012-09-03T11:59:11.113 回答
4
$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);
于 2012-09-03T11:56:36.357 回答
1
$temp = explode(' ', $caption_text);
$matches = array();
foreach ($temp as $element) {
    if ($element[0] == '#') {
       $matches[] = $element;
    }
    else
        $leftoverstring .= ' '.$element;
}

print_r($matches);
echo $leftoverstring;
于 2012-09-03T12:07:11.603 回答
1

你可以试试:

$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;
    }
}
于 2012-09-03T11:56:30.990 回答
1
$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);
于 2012-09-03T11:57:26.763 回答
1

一种可能性是按“”展开,然后检查每个项目是否有标签。如果不是,你可以让其他人再次成为一个字符串。例如:

$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);

希望这有帮助。

于 2012-09-03T11:57:39.227 回答
1
<?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)
?>
于 2012-09-03T12:02:58.693 回答
0
<?php
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
$new = explode(" #",$caption_text);
print_r($new);
?>
于 2012-09-03T11:53:55.187 回答