Matt Backslash
Matt Backslash

Reputation: 804

Get specific string from string, starting with pattern

I receive a string like this:

class1 fa-dollar class2 class3

Now, i need to check this string for a string/word containing fa-*. How can I manage that with PHP?

Wordwise as code

if(custom_strpos($myReceivedString, 'fa-')) {
    echo $faStringOnly;
    // output: 'fa-dollar'
}

Thanks in advance.

Upvotes: 0

Views: 35

Answers (1)

Aaron Saray
Aaron Saray

Reputation: 1177

Let's start with two code examples:

$example = "class1 fa-dollar class2 class3";
if (preg_match_all('/(fa-\w+)/', $example, $matches)) {
  foreach ($matches[0] as $match) {
    print $match . "\n";
  }
}

$moreThan1 = "class1 fa-dollar class2 fa-other class3";
if (preg_match_all('/(fa-\w+)/', $example, $matches)) {
  foreach ($matches[0] as $match) {
    print $match . "\n";
  }
}

First example is your example. We're using preg_match_all to match all instances. In your example, there is only one. The regular expression match is /fa-\w+/ which says "this match begins with fa- and then has 1 or more word-based characters. (I made this assumption based on fa-dollar which I'm assuming are classes from Font Awesome.

The found matches are put into $matches and the exmaple code shows how you can loop through them.

To show that this works with more than one match, you can see the second example.

Upvotes: 1

Related Questions