Extract a specific section from a string

I have a string containing a section of text that I want to extract from a variable. In the line below, I would like to extract something with /in it.

$str = 'this is a random string foo/bar random - string words';

In the above example, I would like to extract foo/bar. I am currently doing this with a explodingstring in spaces, and then iterate over and check to see if each section contains /.

$words = explode(' ', $str);
foreach($words as $word) {
    if(strpos($word, '/') !== false) {
        $myVar = $word;
    }
}

Is there a beeter way to do this since I need to do this for a lot of text strings?

+4
source share
3 answers

, , , /, , -

preg_match_all('%[a-z]+/[a-z]+%', $subject, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
    # Matched text = $result[0][$i];
}

: - https://eval.in/596292

, ,

+3

: preg_match_all("/(\w+\/\w+)[\s|$]/", $str, $output);

$output [1] - .
, , , . , :
last/string/to/test

https://3v4l.org/r8p2g

0

, , . , , . "- a/in it" . , , :

<?php
$str = 'this is a random string foo/bar random - string words - another/example';
preg_match_all('#[^ ]+\/[^ ]+#', $str, $matches);
var_dump($matches);

array (1) {[0] => array (2) {[0] => string (7) "foo / bar"      1 => string (15) "other / example"}}

see here for an example

Of course, this is to some extent a matter of personal taste, if I want to catch something in a greedy way, which I prefer to extract because of the exception.

0
source

All Articles