如何用<code> tags

时间:2019-04-23 15:05:24

标签: php regex

I am trying to take the Jira case details / comments and use the details in our support / utility system and want to replace {code} and {noformat} tags with <code></code> tags so that the formatting is similar to what is shown in Jira

I have tried a few regex expressions with no luck so far.

Here is what I have tried so far

/({code}(?:(?!{code}).)*){code}((?:(?!{code}).)*)/ to replace every other {code} tage with </code> and /{code}/ to then replace the remaining {code} tags with <code>

This also does not take into account the chance that a {code} tag may have {noformat} tags inside and these should not be replaced or vice versa.

Here is the same code I am working with

$jira = new JiraClient\JiraClient('https://jira.url', 'myUser', 'myPass');
try {

    $issue = $jira->issue()->get($ticketJira);

    //$caseBody = $issue->getDescription()

    //For testing Let's Hardset the caseBody

    $caseBody = 'Example Code: {code}{ "fields": { "project": { "key": "JIRA" }, "summary": "Build Jira API into Support Interface to help raise cases.", "description": "Creating of an issue using project\\r\\nkeys and issue type names using the REST API\\r\\n{code}Markup Test{code}", "issuetype": { "name": "Production Task/Issue" }, "customfield_10800": [{"value":"Not applicable"}], "fixVersions": [{"name":"3.0.136.2"},], "versions": [{"name":"3.0.136.2"},] } }{code}';

    // Replace {code} / noformat tags here
      $descRaw = $issue->getDescription();
      $despPre = preg_replace('/({code}+)/', '<code>', $descRaw,1);
      $desc = preg_replace('/(.*(?:(?!{code}).)*){code}((?:(?!.*).)*)/', '\\1</code>\\2', $despPre);


    echo('<label class="control-label">'.$issue->getKey().' - '.$issue->getSummary().'</label>');
    echo("<p class='modal-content' style='text-align: left !important;'>".nl2br($desc)."</p>");
    echo('');
}
catch (\JiraClient\Exception\JiraException $e) {
    echo('<p>'.$e.'></p>');
}

The 2 issues I am having are, the inline tags are also being converted and that I would also want this to work with {noformat} tags instead of having to do a second pass.

1 个答案:

答案 0 :(得分:0)

此人应该做您想做的事:{code}(.*?){code}。与preg_replace()相关联,它将用{code}(或找到之前的<code>)替换所有</code>的出现。

{noformat}替换为<code>的示例:

$str = '{code}var a = 1;{code} then, {noformat}a = 5;{noformat} and, {code}a -= 4;{code}';

$codePatterns = [
    '/{code}(.*?){code}/',
    '/{noformat}(.*?){noformat}/'
];

// output: <code>var a = 1;</code> then, <code>a = 5;</code> and, <code>a -= 4;</code>
echo preg_replace($codePatterns, '<code>$1</code>', $str);

Test this snippet on 3v4l.org


正则表达式的解释:

  • {code}从字面上匹配{code}
  • (.*?) ...
    • ()捕获之间的内容以供以后使用
    • .匹配任何字符,除了换行符
    • *?会在前一个字符的零到无限次之间进行匹配,并尽可能少地匹配
  • {code}从字面上匹配{code}

注意:如果我使用.*而不是.*?,输出将是:

<code>var a = 1;{code} then, <code>a = 5;</code> and, {code}a -= 4;</code>

我想这就是为什么您以这样一个复杂的表达式结尾的原因。