replace spaces between ><
Posted: Fri Aug 12, 2005 10:10 am
ok i have links where i have spaces in the file name but i have to turn those spaces into underscores. basically i need a preg_replace spaces between the > < characters with a _
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
function space2underscore($dir='./')
{
$handle = opendir($dir);
while ($old_name = readdir($handle))
{
$new_name = preg_replace('/> </', '>_<', $old_name);
if (rename($dir.$old_name, $dir.$new_name)) echo $old_name.' => '.$new_name.'<br />';
else echo $old_name.' is not writable for PHP<br />';
}
closedir($handle);
}Code: Select all
preg_replace('/>([^<]+)</e', "str_replace(' ', '_', $1)", $string);Code: Select all
preg_replace('/"([^<]+)"/e', "str_replace(' ', '_', $1)", $other);Code: Select all
function space2underscore($x)
{
return str_replace(' ', '_', $x[1]);
}
echo preg_replace_callback('/<a [^>]+>([^<]+)<\/a>/', 'space2underscore', $string);Code: Select all
function space2underscore($x)
{
return str_replace(' ', '_', $x[1]);
}
echo preg_replace_callback('/<a [^>]*?\bhref="([^>]+)".*?>/', 'space2underscore', $string);Code: Select all
<?php
$tagPattern = '#<\s*\w*(?:\s+[A-z0-9_]+(?:\s*=\s*(["\']?).*?\\1))*[^>]*?>#s';
function underlineAttributes($match)
{
$final = $match[0];
if(preg_match_all('#\s+[A-z0-9_]+(?:\s*=\s*(["\']?)(.*?)\\1)#si',$final,$matches,PREG_OFFSET_CAPTURE))
{
$matches = array_reverse($matches[2]);
foreach($matches as $elem)
{
list($match,$offset) = $elem;
$end = preg_replace('#\s+#','_',$match);
$final = substr_replace($final, $end, $offset, strlen($match));
}
}
return $final;
}
$test = '<asdf qrf="blah blah blah" bif="1234 5678 901234" check=\'1234 1234\' check2=\'1234 " 1234\' ><asdf qrf="blah blah blah" bif="1234 5678 901234" check=\'1234 1234\' check2=\'1234 " 1234\' >';
$result = preg_replace_callback($tagPattern, 'underlineAttributes', $test);
echo 'Input:
'.$test.'
Output:
'.$result;
?>Code: Select all
Input:
<asdf qrf="blah blah blah" bif="1234 5678 901234" check='1234 1234' check2='1234 " 1234' ><asdf qrf="blah blah blah" bif="1234 5678 901234" check='1234 1234' check2='1234 " 1234' >
Output:
<asdf qrf="blah_blah_blah" bif="1234_5678_901234" check='1234_1234' check2='1234_"_1234' ><asdf qrf="blah_blah_blah" bif="1234_5678_901234" check='1234_1234' check2='1234_"_1234' >Code: Select all
if (preg_match_all('/"([^<]+).htm"/e', $other, $regs))
{
for ($ctr=1; $ctr<count($regs); $ctr++)
{
$other = str_replace($regs[$ctr], str_replace(' ', '_', $regs[$ctr]), $other);
}
}