A PHP string containing hashtags without spaces will not be parsed into individual hashtags

I have a challenge where I want to extract individual hashtags from a string that contains hashtags.

Currently, I am utilizing the following code:

preg_match_all('/#([^\s]+)/', $str, $matches);

#test #test #test #example

The code functions correctly when users insert hashtags with spaces between them. However, it encounters issues when the hashtags are directly attached to one another.

#test#test#test#example

Answer №1

Give this a try:

preg_match_all('/#(\w+)/', $str, $matches);

For example:

<?php
$str = '#test #test2 #123 qwe asd #rere#dada';
preg_match_all('/#(\w+)/', $str, $matches);
var_export($matches);

Result:

array (
  0 => 
  array (
    0 => '#test',
    1 => '#test2',
    2 => '#123',
    3 => '#rere',
    4 => '#dada',
  ),
  1 => 
  array (
    0 => 'test',
    1 => 'test2',
    2 => '123',
    3 => 'rere',
    4 => 'dada',
  ),
)

Considering studying Regular Expressions can assist you in tackling these issues effectively.

Answer №2

Here is a solution:

$tags = explode('#', $string);
foreach($tags as $index => $tag)
  $tags[$index] = '#' . $tag;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Style formatting is applied to the addition of fresh content on a webpage

As I develop a front end page that pulls data from multiple sources, my goal is to allow for dynamic addition of new sources without the need for code changes. This includes the ability to add new source URLs on the fly. Additionally, certain data sources ...

The FROM field in PHP email headers is not appearing as expected

I am seeking assistance in setting the FROM field in my email to a specific email address. Currently, it seems to be picking up information from my hosting company's server. [email protected] All other email features are working perfectly fine. ...

Tips for stopping an image from stretching the cell in flexbox using CSS

When using Flexbox to style elements, the width of the parent should be determined by the text inside child1. The image inside child2 should grow proportionately as the parent grows. However, it is important to ensure that the parent div does not exceed it ...

Encountered CORS error when attempting to access the dynamic menu API after logging

Currently, I am working on an Angular 6 and Codeigniter project. In this project, the slider and navigation menu bar are being fetched dynamically through a REST API. Everything runs smoothly until the login process, where a CORS error is encountered. htt ...

JavaScript has been used to modify a cell's URL in jqGrid

Currently, I am utilizing struts2-jqgrid along with JavaScript. After the jqgrid has finished loading, it retrieves <s:url var="updateurl" action="pagosActualizar"/>. Subsequently, in the HTML view source, jqgrid generates options_gridtable.cellurl = ...

What's the best way to center align my tag vertically in this scenario?

I am struggling to center my text vertically in this scenario. Here is the structure I have: <section id='container'> <div id='title'> <h1>Title here.</h1> </div> </section> This ...

Encountering a problem with Laravel's route list functionality

Getting an error message: Error: Ziggy error: route 'contract/generatePDF?id=517&pickupKM=0' is not in the route list. However, it is defined in web.php as follows: GET|HEAD contract/generatePDF Route::get('contract/generatePDF& ...

Find and substitute numerous PHP code lines

Hello there, I am a beginner when it comes to using preg_replace and similar functions so please be patient with me. I have several hundred lines that include this specific line: <strong>[*<a title="*" name="*"></a>]</strong><b ...

Where will the user's input be stored?

Consider the following HTML code: <div class="form-group"> <label class="col-md-3 col-xs-3 col-sm-3 control-label">Phone</label> <div class="col-md-4 col-xs-4 col-sm-4"> <input id="input ...

Incorporate negative padding in order to smoothly scroll to a specific ID

When I jump to an ID using domain.com/#section, the scroll goes too far down and needs a negative margin added. Is there a way to achieve this directly in the URL without relying on CSS, jQuery, or JavaScript? ...

Guide to extracting specific elements from JSON using PHP

After retrieving a JSON from a URL, I am attempting to extract information using PHP. Here is what I have so far: $url = 'https://www.anwb.nl/feeds/gethf'; $result = file_get_contents($url); $array = json_decode($result, TRUE); echo $array[1][ ...

The way images appear can vary between desktop and mobile devices

I am in the process of creating a photography website with a simple goal of displaying images down the page one after another. However, I am encountering issues with uniform display across various desktop and mobile platforms. The site appears perfect on i ...

What could be causing my React components to not display my CSS styling properly?

If you're developing a React application and integrating CSS for components, ensure that you have included the style-loader and css-loader in your webpack configuration as shown below: module.exports = { mode: 'development', entry: &apo ...

What is the most effective method to extract an ID from a URL that is written in various formats?

Does anyone know of a reliable method to extract an ID from various URL formats using javascript or jquery? https://plus.google.com/115025207826515678661/posts https://plus.google.com/115025207826515678661/ https://plus.google.com/115025207826515678661 ht ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...

Is the "sizes" attribute of the "picture" element functional in Chrome when it comes to <source>?

The incredible <picture> element has been functioning flawlessly in the Chrome browser for well over a year, yet regrettably, I seem to be encountering an obstacle when attempting to make use of the powerful sizes attribute within the <source> ...

Obtaining a string value from a parallel array

Apologies for the very basic question, but I'm struggling with this. I have a word. Each letter of the word corresponds to a position in one array, and then returns the character at the same position from a parallel array (basic cipher). Here is my c ...

What advantages does NuSOAP offer over PHP SOAP?

After extensively searching the internet, I've come across numerous articles discussing how to configure NuSOAP and utilize it for setting up a SOAP server and client in PHP. Interestingly, none of these sources highlight any specific advantages of u ...

Utilizing Google Fonts offline without the need for an API

Instead of relying on Google Fonts API to access a variety of fonts for my website, I took matters into my own hands. I downloaded a snapshot of fonts from this GitHub repository: https://github.com/google/fonts and transferred them to my web directory. T ...

Center an element on the screen by dynamically adjusting its position according to the media query

As I work on creating a responsive website that can adapt to screens of various devices, I am facing a challenge. Each device has a different number of pixels, making it difficult to centrally position a div dynamically. Currently, I am using margin-left: ...