Replace in the first instance? I am trying to insert a div that'll call an ad between two paragraphs of copy text.

However, I'd like to do it only one instance. The current replace code I'm using is this - which is inserting my test code multiple times. 

    {% set str = block.bodyText %}
    {{ str | replace('&lt;/p&gt;
    &lt;p&gt;', '&lt;/p&gt;&lt;div id="test"&gt;&lt;/div&gt;&lt;p&gt;') | smartypants }}


Is it possible?
I can't think of a way to do this with Twig's replace filter but it is possible to do it by splitting the text into an array and iterating over it like so:

{% set content %}
  &lt;p&gt;Duis mollis, est non commodo luctus.&lt;/p&gt;
  &lt;p&gt;Nulla vitae elit libero, a pharetra augue.&lt;/p&gt;
  &lt;p&gt;Donec sed odio dui. Maecenas faucibus mollis interdum. &lt;/p&gt;
{% endset %}

{% set inserted %}
  &lt;p&gt;Inserted text&lt;/p&gt;
{% endset %}

{# Split text into array on closing &lt;/p&gt; tags #}
{% for paragraph in content | split('&lt;/p&gt;') %}
  {# Add the closing tag back, except for possible empty lines  #}
  {% set paragraph = paragraph | trim | length ? paragraph ~ '&lt;/p&gt;' : '' %}
  {# Render the text as raw html #}
  {{ paragraph | raw }}
  {# Render the inserted paragraph on the first loop #}
  {% if loop.index == 1 %}
    {{ inserted }}
  {% endif %}
{% endfor %}


Edit: Per your question in the comment about the context, this is a good use case for a macro. This code is untested, but you might try something like this.

{% macro insertAfterFirstParagraph(content, insertContent) %}
  {% for paragraph in content | split('&lt;/p&gt;') %}
    {% set paragraph = paragraph | trim | length ? paragraph ~ '&lt;/p&gt;' : '' %}
    {{ paragraph | raw }}
    {% if loop.index == 1 %}
      {{ insertContent }}
    {% endif %}
  {% endfor %}
{% endmacro %}

{% from _self import insertAfterFirstParagraph %}

{% set addThisHtml %}
  &lt;p&gt;Add this paragraph&lt;/p&gt;
{% endset %}

{% set isAdded = false %}
{% for block in entry.myMatrixField %}
  {% if block.type == 'body' and loop.index &gt; 5 and isAdded == false %}
    {{ insertAfterFirstParagraph(block.bodyField, addThisHtml) }}
    {% set isAdded = true %}
  {% else %}
    {{ block.bodyField }}
  {% endif %}
{% endfor %}


Robin's suggestion to build a custom Twig filter in a plugin (or module) would be the cleanest solution, but the Twig code above should get the job done.

Aside: Craft overrides the default Twig replace filter to use PHP's preg_replace() function but that filter doesn't accept the last two optional arguments, limit and count. If it did, then something like this could have worked:

replace('/&lt;\\/p&gt;\\s+?&lt;p&gt;/', '&lt;/p&gt;&lt;div id="test"&gt;&lt;/div&gt;&lt;p&gt;', 1)


Maybe a feature request is in order.