4

I am using regular expression for getting multiple patterns from a given string. Here, I will explain you clearly.

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

The above is my code.

Here, i am finding the space in a word and replacing the space with the special character what ever i need, right??

Now, I need a regular expression that gives me patterns like

about_us, about-us, aboutus as output if i give about us as input. Is this possible to do. Please help me in that.

Thanks in advance!

7 Answers 7

2

And finally, my answer is

$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;
Sign up to request clarification or add additional context in comments.

Comments

1

You need to do a loop to handle multiple possible outputs :

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

Comments

0

You can try without regex:

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

If you put special characters into an array:

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

Also you can use just str_replace()

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

Comments

0

Not knowing exactly what you want to do I expect that you might want to replace any occurrence of a non-word (1 or more times) with a single dash.

e.g.

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

Comments

0

If you just want to replace the space, use \s

<?php

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

?>

Comments

0

I am not sure that regexes are the good tool for that. However you can simply define this kind of function:

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

$result = rep('about us');

print_r($result);

Comments

0

Matches any character that is not a word character

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

in case its just that... you would get problems if it's a longer string :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.