PHP字符串:如何替换所有“英寸和'到脚?

时间:2011-03-03 10:50:26

标签: php string

我正在尝试将所有'替换为foot字,将"替换为inches字。

我还需要删除所有随附的双引号和单引号。

最终输出应为:

start Rica's 5-1/8 inches another 7 inches here Week 5 foot again 7 foot last clean again hello Mark's end

以下是我的快速示例代码 - 尚未运行。

<?php
$title = 'start Rica\'s 5-1/8" another 7" here ""Week" 5\' again 7\' last \'clean\' again \'hello\' Mark\'s end';

$inches = '"';
$foot = "'";
$inches_word = ' inches';
$foot_word = " foot";

//$pos = strpos($title, $foot);
$pos_inches = strpos($title, $inches);
// check if before the " or ' is a number
$check_number_inches = substr($title, $pos_inches - 1, 1);
if (is_numeric($check_number_inches)) {
    // replace " to inches
    $title = str_replace($inches, $inches_word, $title);
}

$pos_foot = strpos($title, $foot);
// check if before the " or ' is a number
$check_number_foot = substr($title, $pos_foot - 1, 1);
if (is_numeric($check_number_foot)) {
    // replace " to inches
    $title = str_replace($foot, $foot_word, $title);
}

echo $title;
?>

提前致谢:)

3 个答案:

答案 0 :(得分:2)

如果可以接受基于正则表达式的解决方案,您可以这样做:

$title = preg_replace(array("/(\d+)'/","/(\d+)\"/",'/"/',"/'(?!s)/"),
                      array('\1 foot','\1 inches','',''),
                      $title);

Ideone Link

答案 1 :(得分:1)

你只想在数字后出现时替换'或',所以使用带有preg_replace()的正则表达式

$title = 'start Rica\'s 5-1/8" another 7" here ""Week" 5\' again 7\' last \'clean\' again \'hello\' Mark\'s end';

$fromArray = array('/(\d\s*)"/',
                   "/(\d\s*)'/");
$toArray = array('$1 inches', 
                 '$1 foot');


$title = preg_replace($fromArray,$toArray,$title);

给出:

start Rica's 5-1/8 inches another 7 inches here ""Week" 5 foot again 7 foot last 'clean' again 'hello' Mark's end

答案 2 :(得分:0)

你搜索$ inch的第一个实例(只有一个!) 然后你看看之前的字符是否是int。 如果是,则替换所有出现。这毫无意义!