开发者

PHP String: How to replace all " to inches and ' to foot?

开发者 https://www.devze.com 2023-02-14 08:42 出处:网络
I\'m trying to replace all \' to foot word and \" to inches word. I also need to remove all the enclosed double quote and single quote in a word.

I'm trying to replace all ' to foot word and " to inches word.

I also need to remove all the enclosed double quote and single quote in a word.

The final output should be:

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

Below is my quick sample code - not yet working.

<?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_nu开发者_如何学Gomber_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;
?>

Thanks in advance :)


If a regex based solution is acceptable you can do:

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

Ideone Link


You only want to replace ' or " when they appear after a numeric, so use regular expressions with preg_replace() for this

$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);

which gives:

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


You search for the first instance of $inches (only one!!) Then you look if the character before is a int. If so, you replace ALL occurances. This makes no sense!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号