简体   繁体   中英

How to combine Regex with removing space and # character

I have this array, that I need to remove white spaces and # hashtag character:

array (size=7)
  0 => string 'darwin' (length=6)
  1 => string ' #nature' (length=8)
  2 => string ' explore' (length=8)
  3 => string ' galapagos' (length=10)
  4 => string 'karma' (length=5)

  foreach ($feedSinglePosts["hashtags_list"] as $key=>&$item) {
     $item = preg_replace('/(\s|^)/', '', $item);
     $item = preg_replace('/\#+/', '', $item);
  }

The Regex above works well but I want to make it one line if possible . When I do: /(\\s|^)\\#+/ it outputs this:

array (size=7)
  0 => string 'darwin' (length=6)
  1 => string 'nature' (length=6)
  2 => string ' explore' (length=8)
  3 => string ' galapagos' (length=10)
  4 => string 'karma' (length=5)

How to make the regex on liner that removes white spaces and3 hashtag.

It appears that the characters will be at the beginning or end. If so then no need for loops or regex:

array_walk($feedSinglePosts["hashtags_list"], function(&$v) { $v = trim($v, "\n\r #"); });

If you need to remove them anywhere:

$feedSinglePosts["hashtags_list"] = str_replace(["\n","\r"," ","#"], "", $feedSinglePosts["hashtags_list"]);

A non-regex way with array_walk() and trim() ,

<?php
    $array = ['darwin' ,' #nature',' explore', ' galapagos','karma'];
    function remove_hash_space(&$value,$key){
         $value = trim($value,'# ');
     }
    array_walk($array, 'remove_hash_space');  
    print_r($array);
   ?>

DEMO: https://3v4l.org/nOadH

OR with single line array_map() ,

 $array = array_map(function($e){return trim($e,'# ');},$array);  

DEMO: https://3v4l.org/OaS1F

You may use

$arr = ['darwin',' #nature',' explore',' galapagos','karma'];
print_r( preg_replace('~^[\s#]+~', '', $arr) );
// => Array ( [0] => darwin [1] => nature [2] => explore [3] => galapagos [4] => karma )

See the regex demo

The ^[\\s#]+ pattern matches 1 or more occurrences ( + ) of whitespace or # characters ( [\\s#] ) at the start of the string ( ^ ).

If your strings may contain some wierd Unicode whitespace, consider adding the u modifier: ~^[\\s#]+~u .

If you only need to handle horizontal whitespace, replace \\s with \\h .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM