I have content stored in variables and I have a string that users enter in search fields.
My question is how can I chop the text before and after the searched string?
-SearchString
has a the value which user has entered.
-Wholetext
has the whole data from database.
Now, I want to show the Wholetext
as the excerpt like user search for "test" and then I will show the result like:
"text before search string" : "test"
"text after search string" : "_"
Here's my code:
{% block field %}
<div>
{% set SearchString=admin.datagrid.filters.data.value.value %}
<div class="less_resume_container">
{% if SearchString is defined and SearchString in object.data %}
{% set Wholetext= object.data|replace({ (SearchString): '<span style="background-color: #FFFF00;font-size:15px;font-weight:bold">' ~SearchString~'</span>'}) %}
{{ Wholetext|striptags()|truncate(50) }} <a href="javascript:void(0)" class="show_full_resume">Show
more</a>
{% else %}
{% set Wholetext= object.data %}
{{ Wholetext|truncate(50) }} <a href="javascript:void(0)" class="show_full_resume">Show more</a>
{% endif %}
</div>
<div class="full_resume_container" style="display: none;">{{ Wholetext|raw() }}
<a href="javascript:void(0)" class="show_less_resume">View less</a>
</div>
<br/>
</div>
{% endblock %}
Currently it is showing 50 characters from the text. This is not what I want. By the way I am using sonata admin with symfony 2.
You can use a combination of substr and strlen.
substr(WHOLETEXT, 0, (strlen(WHOLETEXT) - strlen(SEARCHTERM)))
Alternatively, you could explode the whole text on the search term, which would leave you with a two part array(assuming your search term only appeared once). The first part would be everything before the search term. The second part would be everything after.
$array = explode(SEARCHTERM, WHOLETEXT);
$before = $array[0];
$after = $array[1];