ابحث عن سلسلة من سلسلة أخرى وأضف هذه السلسلة إلى المصفوفة [مغلق]

StackOverflow https://stackoverflow.com//questions/23007812

سؤال

السلسلة الخاصة بي هي:

$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";

أريد الحصول على #fox, #dog و #lazy من تلك السلسلة وأيضا كل الكلمات التي تحتوي عليها# وأريد إضافة هذه السلسلة إلى مصفوفة مثل هذا:

 $array = array(
       [0]=>'#fox',
       [1]=>'#dog',
       [2]=>'#lazy',
   );

يمكن لأي شخص أن يساعدني..لو سمحت.شكرًا جزيلاً!

هل كانت مفيدة؟

المحلول

يمكنك الاستفادة من هذا التعبير العادي '/#(\w+)/'

<?php
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
preg_match_all('/#(\w+)/', $str, $matches);
array_walk($matches[1],function (&$v){ $v='#'.$v;});
print_r($matches[1]);

انتاج :

Array
(
    [0] => #fox
    [1] => #dog
    [2] => #lazy
)

enter image description here

نصائح أخرى

ها هو:

$s = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
$r = array();
preg_match_all('/(?<!\w)#\w+/', $s,$r);
print_r($r);

باستخدام regex مع preg_match_all تحصل على مجموعة واحدة مع كل الكلمات التي تبدأ بـ # الموجودة في السلسلة.

$str  = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
$pattern = '/(?<!\w)#\w+/';
preg_match_all($pattern, $str , $matches);
print_r($matches);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top