我已将Instagram标题存储在字符串中
类似的东西:
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
我的目标是将字符串拆分为一个包含标记的数组,并将字符串的其余部分保存在变量中
e.g
$matches[0] --> "#beautiful"
$matches[1] --> "#photo" etc..
also $leftoverString="This is a beautiful photo";
任何帮助将不胜感激
答案 0 :(得分: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]);
}
答案 1 :(得分: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);
答案 2 :(得分: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;
}
}
答案 3 :(得分: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);
答案 4 :(得分:1)
一种可能性是通过“”爆炸,然后检查每个项目是否有标签。如果没有,你可以再将其他人变成一个字符串。 e.g:
$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);
希望这会有所帮助。
答案 5 :(得分: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)
?>
答案 6 :(得分:1)
$temp = explode(' ', $caption_text);
$matches = array();
foreach ($temp as $element) {
if ($element[0] == '#') {
$matches[] = $element;
}
else
$leftoverstring .= ' '.$element;
}
print_r($matches);
echo $leftoverstring;
答案 7 :(得分:0)
<?php
$caption_text ="This is a beautiful photo #beautiful #photo #awesome #img";
$new = explode(" #",$caption_text);
print_r($new);
?>