Regular expression to search multiple patterns from a given string

I use regex to get multiple patterns from a given string. Here I will clearly explain to you.

$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag); 

This is my code.

Here I find a space in the word and replace the space with a special character, what do I need, right?

Now I need a regex that gives me patterns like

about_us. about-us, aboutusas output, if I as input about us. Is it possible to do this. Please help me with this.

Thanks in advance!

+4
source share
7 answers

Finally, my answer

$string = "contact_us";
$a  = array('-','_',' ');
foreach($a as $b){
    if(strpos($string,$b)){
        $separators = array('-','_','',' ');
        $outputs = array();
        foreach ($separators as $sep) {
            $outputs[] = preg_replace("/".$b."/", $sep, $string);
        }
        print_r($outputs);  
    }
}

exit;
+2
source

You need to make a loop to process several possible outputs:

$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
 $outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
+1

:

$string      = 'about us';
$specialChar = '-'; // or any other
$newtag      = implode($specialChar, explode(' ', $string));

:

$specialChars = array('_', '-', '');
$newtags      = array();
foreach ($specialChars as $specialChar) {
  $newtags[]  = implode($specialChar, explode(' ', $string));
}

str_replace()

 foreach ($specialChars as $specialChar) {
  $newtags[]  = str_replace(' ', $specialChar, $string);
}
0

, , , - (1 ) .

.

preg_replace('/\W+/', '-', $string);
0

, \s

<?php

$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);

?>
0

, - . ​​:

function rep($str) {
    return array( strtr($str, ' ', '_'), 
                  strtr($str, ' ', '-'),
                  str_replace(' ', '', $str) );
}

$result = rep('about us');

print_r($result);
0

,

$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);

, ... , :)

0

All Articles