PHP String: Как заменить все "в дюймы и футы"? - PullRequest
1 голос
/ 03 марта 2011

Я пытаюсь заменить все ' на 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 ]

2 голосов
/ 03 марта 2011

Если решение на основе регулярных выражений приемлемо, вы можете сделать:

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

Ideone Link

1 голос
/ 03 марта 2011

Вы хотите заменить 'или' только когда они появляются после числа, поэтому используйте регулярные выражения с 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
0 голосов
/ 03 марта 2011

Вы ищете первый экземпляр $ inches (только один !!). Затем вы смотрите, является ли ранее символ int.Если так, вы заменяете ВСЕ вхождения.Это не имеет смысла!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...