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!
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;
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);
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);
}
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);
If you just want to replace the space, use \s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
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);
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 :)
Related
$cont=htmlspecialchars(file_get_contents("https://myanimelist.net/anime/30276/One_Punch_Man"));
function getBetween($string, $start = "", $end = ""){
if (strpos($string, $start)) { // required if $start not exist in $string
$startCharCount = strpos($string, $start) + strlen($start);
$firstSubStr = substr($string, $startCharCount, strlen($string));
$endCharCount = strpos($firstSubStr, $end);
if ($endCharCount == 0) {
$endCharCount = strlen($firstSubStr);
}
return substr($firstSubStr, 0, $endCharCount);
} else {
return '';
}
}
$name=getBetween($cont,'title',' - MyAnimeList.net');
//$name=preg_replace('/[^a-zA-Z0-9 \p{L}]/m', '', $name);
preg_replace('/(*UTF8)[\>\<]/m', '', $name);
trim($name," ");
//$name=str_replace("gt", "", $name);
echo $name;
i want to find the text between title tags. how to do this?
for example in this page title contains 'One Punch Man - MyAnimeList.net' i want to get that
Just use string replace function:
$string = '<BoomBox>';
$string = str_replace('<', '', $string);
$string = str_replace('>', '', $string);
echo $string; // output: Boombox
http://php.net/manual/en/function.str-replace.php
You edited your answer, and we can now see you are dealing with XML/HTML. It's always better to work with the DOM classes. Never use regex! There is a famous Stack Overflow post explaining why never to parse html with regex. Try this solution instead:
<?php
$dom = new DOMDocument();
$dom->loadHTML('<title>BoomBox</title>');
echo $dom->getElementsByTagName('title')->item(0)->textContent;
http://php.net/manual/en/class.domdocument.php
http://php.net/manual/en/class.domnode.php
See it working here https://3v4l.org/EjPQd
You can use preg_replace();, or strip_tags();.
Example preg_replace();:
$str = '> One Punch Man';
$new = preg_replace('/[^a-zA-Z0-9 \p{L}]/m', '', $str);
echo $new;
Output: One Punch Man
Above example will only allow a-z, A-Z and 0-9. You can expand this.
Example strip_tags();:
$str = '<title> BoomBox </title>';
$another = strip_tags($str);
echo $another;
Output: BoomBox
Documentation:
http://php.net/manual/en/function.preg-replace.php // preg_replace();
http://php.net/manual/en/function.strip-tags.php // strip_tags();
You can also use a single call to str_replace with the ['<','>'] as the search argument:
$string = '<BoomBox>';
echo str_replace(['<', '>'], '', $string) . PHP_EOL;
// => Boombox
Or, you may use a regex with preg_replace (especially, if you plan on adding more restrictions for in-context matching to it):
echo preg_replace('~[<>]~', '', $string);
// => Boombox
See the PHP demo.
I have a php function which generates tags from string:
function generate_tags($text)
{
$string = preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $text);
$string = preg_replace('/\s+/', ' ', $string);
$string = mb_strtolower($string, 'UTF-8');
$keywords = explode(' ', trim($string));
foreach($keywords as $key => $value)
{
if((strlen($value)) < 1)
{
unset($keywords[$key]);
continue;
}
}
$result = array_unique($keywords);
$result = array_values($result);
return $result;
}
The string is:
Ke$ha - We Are Who We Are (Cherry Cole Private Booty) Full Oficial Version
But it replaces $ symbol. How can I prevent $ symbol on my function?
Modify the first preg_replace to skip over $ as well:
$string = preg_replace('/[^\p{L}\p{N}\s$]/u', ' ', $text);
Modify the first preg_replace to skip over $ as well:$string = preg_replace('/[^\p{L}\p{N}\s$]/u', ' ', $text);
you just have to press the tick underneath the voting buttons.
How can i remove duplicate commas used in string.
String = ",a,b,c,,,d,,"
I tried rtrim and itrim functions and removed the unwanted commas from beginning and ending .How can i remove duplicate commas ?
Try this:
$str = preg_replace('/,{2,}/', ',', trim($str, ','));
The trim will remove starting and trailing commas, while the preg_replace will remove duplicate ones.
See it in action!
Also, as #Spudley suggested, the regex /,{2,}/ could be replaced with /,,+/ and it would work too.
EDIT:
If there are spaces between commas, you may try adding the following line after the one above:
$str = implode(',', array_map('trim', explode(',', $str)))
i think you can just explode your string and then create a new one getting only relevant data
$string = ",a,b,c,,,d,,";
$str = explode(",", $string);
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
This will output
a,b,c,d
Live Demo
EDITED
If you are having problems with blank spaces you can try use this code
$string = ",a,b,c, ,,d,,";
$str = explode(",", str_replace(' ', '', $string));
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
This should solve spaces issue
Probably not very fast, but a simple method may be:
$str = "a,b,c,,,d";
$str2 = "";
while($str <> $str2) {
$str2 = $str;
$str = str_replace(',,', ',', $str);
}
<?php
$str = ",a,b,c,,,d,,"
echo $str=str_replace(',,','',$str);
?>
Output:
,a,b,c,d
<?php
$str = ",a,b,c,,,d,,"
echo $str=trim(str_replace(',,','',$str),',');
?>
Output:
a,b,c,d
I have a doubt again on RegEx in Php.
Assume that I have a line like this
716/52 ; 250/491.1; 356/398; 382/144
I want the output to be
Replace all semi-colon with comma. I think I can do this using
$myline= str_replace(";", ",", $myline);
Interchange the numbers and replace '/' with a comma. That is, 716/52 will become 52,716. This is where I get stuck.
So, the output should be
52,716 , 491.1,250, 398,356, 144,382
I know that using sed, I can achieve it as
1,$s/^classcode:[\t ]\+\([0-9]\+\)\/\([0-9]\+\)/classcode: \2\,\1/
But, how do I do it using preg_match in php?
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', 'reverse', $str);
function reverse($matches)
{
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}
var_dump($res);
And working sample: http://ideone.com/BeS9j
UPD: PHP 5.3 version with anonymous functions
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', function ($matches) {
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}, $str);
var_dump($res);
As an alternative to Regexen you could try this:
echo join(', ', array_map(
function ($s) { return join(',', array_reverse(explode('/', trim($s)))); },
explode(';', $string)));
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = preg_replace('(\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)', '$2,$1', $str);
$str = str_replace(';', ',', $str);
Uses two capture groups, replacing them in reverse order. See it here.
How can I make upper-case the first character of each word in a string accept a couple of words which I don't want to transform them, like - and, to, etc?
For instance, I want this - ucwords('art and design') to output the string below,
'Art and Design'
is it possible to be like - strip_tags($text, '<p><a>') which we allow and in the string?
or I should use something else? please advise!
thanks.
None of these are really UTF8 friendly, so here's one that works flawlessly (so far)
function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI"))
{
/*
* Exceptions in lower case are words you don't want converted
* Exceptions all in upper case are any words you don't want converted to title case
* but should be converted to upper case, e.g.:
* king henry viii or king henry Viii should be King Henry VIII
*/
$string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
foreach ($delimiters as $dlnr => $delimiter) {
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $wordnr => $word) {
if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtoupper($word, "UTF-8");
} elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtolower($word, "UTF-8");
} elseif (!in_array($word, $exceptions)) {
// convert to uppercase (non-utf8 only)
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}//foreach
return $string;
}
Usage:
$s = 'SÃO JOÃO DOS SANTOS';
$v = titleCase($s); // 'São João dos Santos'
since we all love regexps, an alternative, that also works with interpunction (unlike the explode(" ",...) solution)
$newString = preg_replace_callback("/[a-zA-Z]+/",'ucfirst_some',$string);
function ucfirst_some($match)
{
$exclude = array('and','not');
if ( in_array(strtolower($match[0]),$exclude) ) return $match[0];
return ucfirst($match[0]);
}
edit added strtolower(), or "Not" would remain "Not".
How about this ?
$string = str_replace(' And ', ' and ', ucwords($string));
You will have to use ucfirst and loop through every word, checking e.g. an array of exceptions for each one.
Something like the following:
$exclude = array('and', 'not');
$words = explode(' ', $string);
foreach($words as $key => $word) {
if(in_array($word, $exclude)) {
continue;
}
$words[$key] = ucfirst($word);
}
$newString = implode(' ', $words);
I know it is a few years after the question, but I was looking for an answer to the insuring proper English in the titles of a CMS I am programming and wrote a light weight function from the ideas on this page so I thought I would share it:
function makeTitle($title){
$str = ucwords($title);
$exclude = 'a,an,the,for,and,nor,but,or,yet,so,such,as,at,around,by,after,along,for,from,of,on,to,with,without';
$excluded = explode(",",$exclude);
foreach($excluded as $noCap){$str = str_replace(ucwords($noCap),strtolower($noCap),$str);}
return ucfirst($str);
}
The excluded list was found at:
http://www.superheronation.com/2011/08/16/words-that-should-not-be-capitalized-in-titles/
USAGE: makeTitle($title);